Switch Background Image using Backstretch.js

Sam Deering
Tweet

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
   ========================================================================== */

(function($,W,D,undefined)
{
     var JQUERY4U = {};
     JQUERY4U.BG =
     {
         cache: {},
         init: function()
         {

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

                console.log('updateBgImage....');

                //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 */
                $.backstretch([
                    bgImage
                ], {
                    centeredY: false
                });


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

            //detect actions on window resize
            $(window).on("resize", function()
            {
                updateBgImage();
            });

            //init bg image
            updateBgImage();

         }
     }

     $(function() {
        JQUERY4U.BG.init();
     });

})(jQuery, window, document);

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Andrew

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

  • http://www.freelancetoindia.com/ Freelancetoindia.com

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