Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery addClass with if condition

I'm trying to add a class to an image if the height of the image is smaller than the height of the containing div. However, jQuery adds the class to all images if one image is smaller than the containing box. How do I get the jquery to only add the class to the images that are smaller than the containing divs?

I have experience with jQuery whatsoever. This is the first code I ever wrote in jQuery.

$('.expositie, .right img').each(function(){
     if ($(".expositie").height() > $(".right img").height()) {
     $(".right img").addClass("toggle");
     }
});
like image 683
Fabian Avatar asked Feb 08 '14 14:02

Fabian


1 Answers

You could use addClass function parameter too, some find it less readable though:

$('.expositie').find('.right img').addClass(function(){
    return $(this).closest(".expositie").height() > $(this).height() ? "toggle" : "";
});
like image 58
A. Wolff Avatar answered Sep 20 '22 03:09

A. Wolff