jQuery addClass with if condition
Asked Answered
S

2

6

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");
     }
});
Signatory answered 8/2, 2014 at 14:30 Comment(1)
Are you sure there should be a comma in your first selector ? I'm not really sure of the intent.Deferment
T
7

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" : "";
});
Thy answered 8/2, 2014 at 14:43 Comment(0)
M
1

Like this :

$('.expositie, .right img').each(function(){
     if ($(this).closest(".expositie").height() > $(this).height()) {
         $(this).addClass("toggle");
     }
});

closest lets you find the first enclosing element verifying a given selector.

You could also use filter which I find clearer:

$('.expositie, .right img').filter(function(){
    return $(this).height()<$(this).closest(".expositie").height()
}).addClass("toggle");

EDIT : I have a doubt about your intent. Should there be a comma in the first selector ?

Mean answered 8/2, 2014 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.