Forked from A Non Ymous's Pen sJAdx.
A Pen by Bryan Buchanan on CodePen.
Forked from A Non Ymous's Pen sJAdx.
A Pen by Bryan Buchanan on CodePen.
<img src="#" width="1000" height="500" data-dimensions="1000x500"> | |
<img src="#" width="1000" height="500"> | |
<img src="#" data-dimensions="1000x500"> | |
<img src="#"> |
(function($) { | |
$.fn.getImageSizeWhileLoading = function(parameters) { | |
parameters = parameters || {}; | |
var defaults = { | |
findDimension: 'width' | |
}; | |
parameters = $.extend(defaults, parameters); | |
return this.each(function() { | |
$(this).find('img').each(function() { | |
var $image = $(this); | |
if ($image.data('dimensions')) { // Use 'dimensions' data attr, if present | |
var aspectRatio = $image.data('dimensions').split('x'); | |
var aspectRatio = aspectRatio[0] / aspectRatio[1]; | |
} else { // Otherwise, use width/height attr | |
var aspectRatio = $image.attr('width') / $image.attr('height'); | |
} | |
if (parameters.findDimension === "width") { | |
var newHeight = parseInt($image.css('height')); | |
var newWidth = Math.round(newHeight * aspectRatio); | |
} else { | |
var newWidth = parseInt($image.css('width')); | |
var newHeight = Math.round(newWidth / aspectRatio); | |
} | |
$image.css({ | |
width: newWidth + 'px', | |
height: newHeight + 'px' | |
}); | |
}); | |
}); | |
}; | |
})(jQuery); | |
$(document).ready(function() { | |
$('body').getImageSizeWhileLoading(); | |
}); |
img { | |
width: auto; | |
height: 200px; | |
} |