Skip to main content

Switch Background Image using Backstretch.js

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Get practical advice to start your career in programming!


Master complex transitions, transformations and animations in CSS!