JSFiddle - React, Tailwind, and code Playground

by rodneyrehm

HTML

<img class="responsive" src="http://dummyimage.com/600x400/000/fff.png&text=Image+1" data-res1="http://dummyimage.com/600x400/333/f00.png&text=Image+2">

<button class="change-resolution" data-to="res0">Default</button>
<button class="change-resolution" data-to="res1">Resolution 1</button>

CSS

body.res1 img.responsive {
    /* 
        works nowhere
        content: attr(data-res1, url);
    
        works in webkit, but not firefox
        content: url("http://dummyimage.com/600x400/333/f00.png&text=Image+2");
    
        conclusion:
        switching out image content via CSS is (currently) not an option
    */
}

body.res0 button[data-to=res0],
body.res1 button[data-to=res1] {
    background: navy;
    color: white;
}

JavaScript

var $body = $(document.body),
    resolutions = "res0 res1 res3",
    widths = {
        res0: '',
        res1: '(min-device-width:320px and max-device-width:640px)'
    };

$body.addClass('res0').on('click', '.change-resolution', function(e) {
    // required to react to resultion via CSS
    var to = $(this).data('to');
    if (!$body.hasClass(to)) {
        $body.removeClass(resolutions).addClass(to);
    }
    
    var transitioning = 0;
    // start some spinner animation
    
    // replace responsive image sources
    $('img.responsive').attr('src', function() {
        var $this = $(this);
        // populate res0
        if (!$this.data('res0')) {
            $this.data('res0', $this.attr('src'));
        }
        
        transitioning++;
        
        // load event doesn't bubble
        $this.off('load').one('load', function(e) {
            transitioning--;
            if (!transitioning) {
                // end some spinner animation
            }
        });
        
        // set new resolution
        return $this.data(to);
    });
});