I'm trying to resize images when a page is loaded and when the browser is resized. Some images will be portrait and some landscape, and they will be in a container div that also may be portrait/landscape (depending on browser size). It doesn't matter if the image should be stretched to fill the box (either 100% width or 100% height) and if the ratio's do not match then clipping will occur (through CSS overflow:hidden
).
My method was to get the ratio of the container box (ie portrate or landscape) and get the image ratio (portrait or landscape), compare them and adjust the CSS width/height accordingly.
Note: all the containers will have a class of mr_our-dest-img-container
and will all only contain 1 img element (and some different elements).
Here is the code I have, which doesn't work. It doesn't do anything, and I can't figure it out. Could anyone help me fix this?
$(document).ready(function () {
updateImageSize();
$(window).resize(function() {
updateImageSize();
});
});
function updateImageSize() {
$(".mr_our-dest-img-container").each(function(){
var ratio_cont = jQuery(this).width()/jQuery(this).height();
var $img = jQuery(this).find("img");
var ratio_img = $img.width()/$img.height();
if (ratio_cont > ratio_img)
{
$img.css({"width": "100%", "height": "auto"});
}
else if (ratio_cont < ratio_img)
{
$img.css({"width": "auto", "height": "100%"});
}
}
};
It is an syntax error just as the console said. You miss a )
after the each
function end.
function updateImageSize() {
$(".mr_our-dest-img-container").each(function(){
var ratio_cont = jQuery(this).width()/jQuery(this).height();
var $img = jQuery(this).find("img");
var ratio_img = $img.width()/$img.height();
if (ratio_cont > ratio_img)
{
$img.css({"width": "100%", "height": "auto"});
}
else if (ratio_cont < ratio_img)
{
$img.css({"width": "auto", "height": "100%"});
}
}); //missing )
};