Add and remove Jquery class

Asked

Viewed 2,719 times

1

I have a toggle effect that opens and closes a div, and in this effect, I put to add a class and remove. It adds the class, but is not removing it. Why?

Jquery

$j('.filters__filter.tamanho').click(function(){
    $j('.filters__filter.tamanho .ul--0').slideToggle(150);
    //remove class active
    $j('.filters__filter.tamanho').removeClass('active');
    //adiciona class active ao item clicado
    $j('.filters__filter.tamanho').addClass('active');
}); 

If I click again, the active class

  • 4

    You are ordering him to remove the class and then you add it again?

  • Yeah, it got confused kk, I’ve tried so hard to do this here, I’m not getting it. How do I make it add when it’s selected, and when it’s clicked again or another div is selected, it removes the class? Is there any way or in the next selected div code, I will have to have that div removed? Thanks!

2 answers

2

If you have several elements and you want to remove the class to all that were not clicked (and have toggle of the class on clicked) you can do so:

var filtros = $j('.filters__filter.tamanho');
filtros.click(function(e){
    filtros.each(function(){
        if (this == e.currentTarget) $(this).toggleClass('active').slideToggle(150);
        else $(this).removeClass('active');
    });
});

So you remove the class at all, and you toggle what was clicked.

  • Sergio, I think you just don’t have the need to make a foreach in filters, just remove all assets filtros.removeClass('active') and as you are in the click scope, the this is the element that was clicked, so just run directly $(this).toggleClass('active').slideToggle(150); https://jsfiddle.net/L4Lfa7r3/

  • 1

    @Pedrocamarajunior when we do filtros.removeClass('active') he runs a each in the same internally to take the class one by one. Hence with my solution it saves an extra execution when the this == e.currentTarget. But I agree it would be 2 lines more compact.

  • I agree with your point as well, but particularly prefer the cleaner code. :)

1


let filtersSize = jQuery('.filters__filter.tamanho')
filtersSize.on('click', function() {
    filtersSize.find('.ul--0').slideToggle(150)

    // toggle active class
    filtersSize.toggleClass('active')
})

Try this here brother.. toggleClass will alternate the class..

  • Thank you Drik, simple and solved my problem, did not remember the toggleClass. Again, thank you!

  • Fecho brother, é nois!

  • 1

    $j('.filters__filter.tamanho').toggleClass('active'); will toggle all elements (!). If all have no class active anyone who is clicked makes everyone stay with the class active...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.