You might want to call this function on window.load
:
$('img:visible').each(function() {
// For visible images only
var imageWidth,
imageHeight,
aspectRatio;
var parentWidth = $(this).parent().width(),
parentHeight = $(this).parent().height();
if (this.naturalWidth > parentWidth || this.naturalHeight > parentHeight) {
aspectRatio = this.naturalWidth / this.naturalHeight; // Actual image width and height
if (this.naturalWidth > this.naturalHeight) {
imageWidth = parentWidth - 50; // Leave margin
imageHeight = imageWidth / aspectRatio;
} else {
imageHeight = parentHeight - 10; // Leave some space
imageWidth = imageHeight * aspectRatio;
}
$(this).css({
'width': imageWidth,
'height': imageHeight
});
}
});
Demo: https://jsfiddle.net/tusharj/onytgawp/