I have multiple images and want to find out if each image horizontal or vertical and add a class to it so I can style it accordingly.
I tried multiple things including something like this:
if ($(".img").width() > $(".img").height()) {
$(this).addClass("horizontal");
}
What am I doing wrong? Thank you!
Your code is not working because of $(this)
. this
is not pointing to the image element here but it is pointing to most recent instance of the scope.
Try this which will use jQuery each
loop to loop through all the image elements and then add the required class conditionally.
$("img").each(function(){
var $this = $(this);
if ($this.width() > $this.height()) {
$this.addClass("horizontal");
}
});
If you have a class ".img"
to all the image elements then you can use the class selector.
$(".img").each(function(){
var $this = $(this);
if ($this.width() > $this.height()) {
$this.addClass("horizontal");
}
});
Alternatively you can use jQuery filter
method to filter all the images which have width greater than height and then add the required class at once.
$(".img").filter(function()
var $this = $(this);
return $this.width() > $this.height();
}).addClass("horizontal");
.filter()
- Reduces the set of matched elements to those that match the selector or pass the function's test.
If you are doing this on page load then make sure you execute this code inside window load event which will ensure that all the images are loaded.
$(window).load(function(){
$(".img").each(function(){
var $this = $(this);
if ($this.width() > $this.height()) {
$this.addClass("horizontal");
}
});
});