Adding and removing JQuery class

1

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

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, class active

    
asked by anonymous 24.04.2017 / 19:45

2 answers

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 toggle the class ..

    
24.04.2017 / 19:52
2

If you have several elements and want to remove the class from all that were not clicked (and have toggle the class in the clicked) you can do this:

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.

    
24.04.2017 / 19:54