I need to fit images to the viewport/window size.
I use this code for doing it:
$(".fittedImg").each(function () {
// I want to limit the size, and show a scrollbar on very small viewport
height = ($(window).height() < 725) ? 725 : $(window).height();
width = ($(window).width() < 1150) ? 1150 : $(window).width();
var newWidth, newHeight;
$(this)
.removeAttr("height")
.removeAttr("width"); // reset img size
// calculate dimension and keep it
if (($(this).width() / width) > ($(this).height() / height)) {
newHeight = height;
newWidth = height / ($(this).height() / $(this).width());
} else {
newHeight = width / ($(this).width() / $(this).height());
newWidth = width;
};
$(this).stop(true, false).animate({
"height": newHeight + "px",
"width": newWidth + "px"
});
});
I wrapped that code in a function which I call on resize, and on events such as $(‘.fittedImg’).load() and $(‘.fittedImg’).ready().
The result’s very weird:
In Chrome it normally works, but somtimes the images stretch on repeated refreshes. On IE there’s quite the same problem. Opera does not fail never and safari ignore the calculation at all (ever stretching).
What’s wrong with my calculation and/or events calling?
Thank you.
Assuming you want to fit the image inside a containing element (in this case the
window), here are some simpler calculations you might find useful. The concept is quite simple, based on the containing measures and the image measures, calculate a ratio. Then multiply it with the original measures:Please note that some extensions such as AdBlock can mess up the extracted width/height from the image. You can console and text the
imgWidth/imgHeightjust to make sure that it is available.Also please note that chances are that your image is already loaded when this event is added, depending on how you place your code. In that case, you should check for the
completeproperty on the IMG element: