I'm trying to use jQuery to detect the orientation of a number of images. Once detected, I want to add a class to indicate this i.e .landscape
.
The code below seems to only be assessing the first image it comes across, and then applying that to all subsequent images. For example, if the first image is landscape, this will be applied to all images including portrait or square image.
Am I misusing the .each()
statement?
Thank you.
HTML
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="200" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="200" data-height="100" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="100" />
</div>
JQUERY
// Detect image orientation
$('.carousel-cell').each(function () {
"use strict";
var img = $('img');
if (img.attr('data-width') > img.attr('data-height')){
// Landscape
img.removeClass().addClass('landscape');
} else if (img.attr('data-width') < img.attr('data-height')){
// Portrait
img.removeClass().addClass('portrait');
} else {
// Equal (Square)
img.removeClass().addClass('square');
}
});