Reputation: 13
function ratioDetect () {
var contWidth = $('.thumbnail-container').width()
var contHeight = $('.thumbnail-container').height()
var imgWidth = $('.thumbnail-container img').width()
var imgHeight = $('.thumbnail-container img').height()
var contRatio = contWidth/contHeight
var imgRatio = imgWidth/imgHeight
if (contRatio > imgRatio) {
$('.thumbnail-container img').removeClass('full-height')
$('.thumbnail-container img').addClass('full-width')
}
else{
$('.thumbnail-container img').removeClass('full-width')
$('.thumbnail-container img').addClass('full-height')
}
}
It should be pretty clear what this function does, the problem is I have 6 of these "thumbnail-container" so the script just get the values from the FIRST container only and does this math based just on the img inside this container and applies the values to all the other images.
I've tried to follow some tutorial for the ".this" usage but I failed. I need this code act separately for each individual container and his child-img because the size of each of the 6 <img>
s is different.
Upvotes: 1
Views: 601
Reputation: 388416
You need to iterate over the container and process
function ratioDetect() {
$('.thumbnail-container').each(function () {
var $this = $(this),
$img = $this.find('img'),
contWidth = $this.width(),
contHeight = $this.height(),
imgWidth = $img.width(),
imgHeight = $img.height();
var contRatio = contWidth / contHeight,
imgRatio = imgWidth / imgHeight;
if (contRatio > imgRatio) {
$img.removeClass('full-height');
$img.addClass('full-width');
} else {
$img.removeClass('full-width');
$img.addClass('full-height');
}
});
}
Upvotes: 2