Image Size : Cover jQuery Hack

Image Size to Cover, jQuery Hack

by Arif Reza

HTML

<div class="image-container">
  <img src="https://s3-ap-southeast-1.amazonaws.com/apexasws3imagetest/images/thumbs/0005798_sprint-mens-canvas.jpeg" alt="Men's Canvas">
</div>

<div class="image-container">
  <img src="https://images.unsplash.com/photo-1503803548695-c2a7b4a5b875?ixlib=rb-1.2.1&w=1000&q=80" alt="Beach" class="beach">
</div>

<div class="image-container">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Madame_X_%28Madame_Pierre_Gautreau%29%2C_John_Singer_Sargent%2C_1884_%28unfree_frame_crop%29.jpg/1200px-Madame_X_%28Madame_Pierre_Gautreau%29%2C_John_Singer_Sargent%2C_1884_%28unfree_frame_crop%29.jpg" alt="Beach">
</div>

<div class="image-container">
  <img src="https://www.history.com/.image/c_fit%2Ccs_srgb%2Cfl_progressive%2Cq_auto:good%2Cw_620/MTU3ODc5MDgzNDgxMTc5ODcx/huey-long2.jpg" alt="Beach">
</div>

<div class="image-container">
  <img src="https://cdn.britannica.com/06/190406-050-A305FF00/oil-Alice-canvas-Amedeo-Modigliani-Copenhagen-National-1918.jpg" alt="Beach">
</div>

SCSS

.image-container {
  width:80px;
  height:80px;
  overflow:hidden;
  
  img {
    width:100%;
    height:100%;
  }
}

JavaScript

// Initialize jQuery sizeCover Method
(function( $ ){
   $.fn.sizeCover = function() {
      var $elem = this;
      var $parent = $elem.parent();

      getImageDimensions($elem.attr('src'), function(dim){
        if (dim.height>dim.width){
          $elem.css({
            width: '100%',
            height: 'auto',
            marginTop: '-' + (($parent.width()/dim.width)*dim.height-$parent.height()) / 2 + 'px'
          })
        } else if (dim.width>dim.height){
          $elem.css({
            width: 'auto',
            height: '100%',
            marginLeft: '-' + (($parent.height()/dim.height)*dim.width-$parent.width()) / 2 + 'px'
          })
        }
      });
      
      return this;
   }; 
   
   function getImageDimensions(path,callback){
    var img = new Image();
    img.onload = function(){
      callback({
        width : img.width,
        height : img.height
      });
    }
    img.src = path;
  }
})( jQuery );


// Usage
$(function(){
	$('.image-container>img').each(function(index,elem){
    $(elem).sizeCover();
  });
});