Skip to content

Instantly share code, notes, and snippets.

@bryanbuchanan
Created July 18, 2014 20:55
Show Gist options
  • Save bryanbuchanan/5c0a7715cf27bea578cf to your computer and use it in GitHub Desktop.
Save bryanbuchanan/5c0a7715cf27bea578cf to your computer and use it in GitHub Desktop.
A Pen by Bryan Buchanan.
<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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment