I’m trying to create an easy method to get responsive images for my web sites.
Check it working on this demo page.
In this case I’m gonna show I’ll get responsive background for an specific panel.
<div data-responsive-bg="360,[IMG_MEDIUM];768,[IMG_BIG]">style="background-image:url([IMG_SMALL]);">
By default the panel will show an small version of the image. As this image has a smaller weight, it’ll make the page load faster. For small devices we’ll keep it like that, but with Javascript the plugin search, depending of the panel width, if we provide a better image for this case.
With jQuery the plugin search all the panels that has an attribute: data-responsive-bg. This attribute show in key,value format all the different versions of the image that we are gonna provide. In the previous case we have two image:
- [IMG_MEDIUM] to be show when the panel is wider than 360 pixels
- [IMG_BIG] to be show when the panel is wider than 768 pixels
function setResponsiveImages() { $('[data-responsive-bg]').each(function () { var t = $(this), w = t.width(), data = t.data('responsive-bg'), measure, size, url; data.split(';').forEach(function(measure) { measure = measure.split(','); size = measure[0]; if ( w > size ) { url = measure[1]; } }); if ( url ) { t.css('background-image', 'url('+url+')'); } }) }
I use this method to init this function, an check it again when user change the window width:
var canvasResize = 0; $(window).resize(function(){ clearTimeout(canvasResize); canvasResize = setTimeout(function(){ setResponsiveImages(); }, 200); }); $(window).resize();
You can check it working on this demo page.