Search code examples
javascripthtmlresponsive-designmootoolspicturefill

Responsive background images


Currently I'm working on building a solution for having responsive background images set via JavaScript. I am using Picturefill to create cross-browser support.

What do I need? There is an element on my page which needs a pretty little background photo. On the page there is a picture element which loads conditionally images. However I specified one default image source if the browser doesn't have proper picture element support.

With MooTools I check what photo is supposed to show up on domready, on window resize I check my image 'src' again to replace my current picture if needed (with a bigger or smaller one).

In FireFox the picture element replaces the image 'src' in the DOM, it works perfect!

Chrome (and IE) don't replace the image 'src' so my photo will always have the default photo dimensions according to MooTools. However, when you hover over the image 'src' via the Chrome developer tools it does show the correct image source for that media query.

I can get in way too many details but trust me I really need to do it like mentioned above, who want to help me with this? :)

<script>
    var Placeholder = $('Placeholder');

    var CoverImage = $('MyCover').getElement('img').src;

    Placeholder.setStyle('background-image', 'url(' + CoverImage + ')');

    var $timer = null;

    window.addEvent('resize', function(){

        var ResponsiveImage = function(){

            var $ResponsiveImage = $('MyCover').getElement('img').src;

            $('Placeholder').setStyle('background-image', 'url(' + $ResponsiveImage + ')');
        };

        clearTimeout($timer);
        $timer = ResponsiveImage.delay(250, this);
    });
</script>

<picture>
    <source media="all and (max-width: 30em)" srcset="1.jpg">
    <source media="all and (min-width: 30.063em) and (max-width: 48em)" srcset="2.jpg">
    <source media="all and (min-width: 48.063em) and (max-width: 80em)" srcset="3.jpg">
    <source media="all and (min-width: 80.063em)" srcset="4.jpg">

    <img src="2.jpg">
</picture>

Thanks for the possible solutions, I am very grateful!

Cheers, Stefan


Solution

  • I am using the currentSrc property to get the updated image source and it works like a charm! Thanks everyone for the help!