Switch Background Image using Backstretch.js

By Sam Deering

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);

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • 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

Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.