Code snippet to Switch Background Image using Backstretch.js and Underscore.js. Useful if you need to show a different background image for a desktop and mobile. I’m just using underscore.js for the debounce on window resize event it’s not essential.

* smart window resize capture
* choose correct bg image to load for browser width
* switch bg image when browser resized to less 640 width (mobiles)

/* ==========================================================================
   Update Background Image using Backstretch.js and Underscore.js
   ========================================================================== */

     var JQUERY4U = {};
     JQUERY4U.BG =
         cache: {},
         init: function()

            // Create the listener function (debounce).
            var updateBgImage = _.debounce(function(e) {


                //switch to mobile version background for lower res devices.
                var bgImage = (window.innerWidth > 640) ? "/img/home-bg.jpg" : "/img/home-bg-mobile.jpg";

                /* backstretch responsive bg image */
                ], {
                    centeredY: false

            }, 500); // Maximum run of once per 500 milliseconds

            //detect actions on window resize
            $(window).on("resize", function()

            //init bg image


     $(function() {

})(jQuery, window, document);
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Andrew

    dude this is the coolest thing ever – EXACTLY what i was looking for. cannot thank you enough!!


    It’s really amazing stuff. I like it. Thanks for sharing such a great resource.

  • D.P.

    Hello, I’m using Blogger’s Picture Window template and I’d like to add a textured image to the POST’S background (NOT the blog background). I’m having difficulty finding an image that will fit the posts width and height. Will this script fix that? Does the image have to be a certain size? If so, what are they?

    I am also a newbie to blogging and know very little about programming. I do know how to cut and paste, though. :)

    Thanks for your input and time.

  • Brad Dalton

    You can use the featured image meta box to display a different image for the background or header on each post or page using backstretch

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.