Skip to content

Instantly share code, notes, and snippets.

@mohsinrasool
Created July 29, 2015 13:54
Show Gist options
  • Save mohsinrasool/e486f0d562588fcf5956 to your computer and use it in GitHub Desktop.
Save mohsinrasool/e486f0d562588fcf5956 to your computer and use it in GitHub Desktop.
Javascript function to load the corresponding image based on window resolution.
/**
* Javascript function to load the corresponding image based on window resolution.
*
* Usage:
* <div id='story' data-adaptive-bg='{
* "desktop": "/static/img/banners/press/press-1920x1080.jpg",
* "tablet": "/static/img/banners/press/press-992x500.jpg",
* "mobile": "/static/img/banners/press/press-768x400.jpg"
* }'>
* </div>
*
*/
function loadAdaptiveBackground() {
var initialize = true, screen = "desktop", cache = {};
var _loadAdaptiveBackgroundHandler = function() {
var width = $(window).width();
if ((width < 768 && screen !== 'mobile') || (width >= 768 && width < 992 && screen !== 'tablet') || (width >= 992 && screen !== 'desktop') || initialize) {
initialize = false;
$('[data-adaptive-bg]').each(function () {
var data = $(this).data('adaptive-bg'), $el = $(this), url;
if (width < 768) {
screen = 'mobile';
url = (data.mobile || data.desktop);
} else if (width >= 768 && width < 992) {
screen = 'tablet';
url = (data.tablet || data.desktop);
} else {
screen = 'desktop';
url = (data.desktop);
}
if (!cache.hasOwnProperty(url)) {
var $tmp = $('<img/>').attr('src', url).hide().appendTo('body');
$tmp.on('load', function () {
$el.css('background-image', 'url(' + url + ')').animate({opacity: 1});
$tmp.remove();
});
} else {
$el.css('background-image', 'url(' + url + ')');
}
});
}
};
$(window).resize(_loadAdaptiveBackgroundHandler);
_loadAdaptiveBackgroundHandler();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment