Image Resizer (jQuery)

by Kevin Pliester

HTML

<img 
  src="http://via.placeholder.com/300x150"  
  data-small="http://via.placeholder.com/300x150"
  data-tablet="http://via.placeholder.com/768x150" 
  data-desktop="http://via.placeholder.com/1080x150" 
  data-large="http://via.placeholder.com/1800x150"
/>

CSS

img {
  width: 100%;
  height: auto;
  display: block;
}

JavaScript

/**
 * Maschine Image Resizer
 *
 * Author: Devhats
 * Version: 1.0
 */
(function($) {

  $.fn.extend({

    maschineImageSizer: function() {

      return this.each(function() {

        var imageSelector = $(this);

        $(imageSelector).each(function() {

          var currentImage = $(this);

          // max width 768px (mobile)
          if (window.matchMedia('(max-width: 768px)').matches) {
            currentImage.attr('src', currentImage.data('small'));
          }

          // min width 768px (tablet)
          if (currentImage.data('tablet')) {
            if (window.matchMedia('(min-width: 768px)').matches) {
              currentImage.attr('src', currentImage.data('tablet'));
            }
          }

          // min width 1080px (desktop)
          if (currentImage.data('desktop')) {
            if (window.matchMedia('(min-width: 1080px)').matches) {
              currentImage.attr('src', currentImage.data('desktop'));
            }
          }

          // min width 1800px (large)
          if (currentImage.data('large')) {
            if (window.matchMedia('(min-width: 1800px)').matches) {
              currentImage.attr('src', currentImage.data('large'));
            }
          }
        });
      });
    }
  })
})(jQuery);

// usage
jQuery(function($) {

	// check EACH selector
  $('img').maschineImageSizer();
  
  // check EACH selector on resize
	$(window).on('resize', function(){
  	$('img').maschineImageSizer();
  });

});