Huma Ali Huma Ali - 4 months ago 9
jQuery Question

Adding and removing class in jquery

I'm trying to show/hide my div elements using

slidetoggle
and
slideDown
. Its working perfectly fine.
Now what I'm trying to do is, I want to
addClass
'visible-divs' to the visible divs only and
removeClass
when they get hidden.

Problem is, the class is added succesfully but it doesn't remove the class when it
slides up
to hide them. What am I doing wrong?



$(".OffersContainer > div:gt(0)").hide();

$(".OffersContainer > span").click(function() {
this.clickCount = (this.clickCount || 0) + 1
var command = this.clickCount % 3 === 0 ? 'slideToggle' : 'slideDown';
$(this).siblings(this.clickCount % 3 === 1 ? "div:lt(3)" : "div:gt(0)")[command]();
$('.pan-box').filter(':visible').addClass("visible-divs");
$('.pan-box').filter(':hidden').removeClass("visible-divs");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="OffersContainer">
<div class='pan-box'>A</div>
<div class='pan-box'>B</div>
<div class='pan-box'>C</div>
<div class='pan-box'>D</div>
<div class='pan-box'>E</div>
<span>Show more</span>
</div>




Answer

For this to work you need to select the :visible/:hidden elements after the animation completes. To do this, use the callback function parameter:

$(".OffersContainer > span").click(function() {
    this.clickCount = (this.clickCount || 0) + 1
    var command = this.clickCount % 3 === 0 ? 'slideToggle' : 'slideDown';
    $(this).siblings(this.clickCount % 3 === 1 ? "div:lt(3)" : "div:gt(0)")[command](function() {
        $('.pan-box').filter(':visible').addClass("visible-divs");
        $('.pan-box').filter(':hidden').removeClass("visible-divs");
    });
});

Updated fiddle

As an aside, what's the point of changing a class on a hidden element? By definition the effect won't be seen. You can just use the :hidden selector alone if you want to know which elements are hidden

Comments