macgera
macgera

Reputation: 409

Watch elements count by class using jQuery

I have simple HTML:

ul > li > button

And have some JavaScript code:

$('.side-filters .filters_list li').each(function(){
    $(this).find('button').click(function(){

        var arrList = $('.side-filters .filters_list li .active').map(function(){
            return $(this).attr('id');
        }).get();

        if($(this).hasClass('active')) {
            $(this).removeClass('active');

        } else {
            $(this).addClass('active');
        }
    });
});

If I click on a button, add class 'active' to the button, and if clicked again, remove class.

I need live count elements witn class 'active'. If there is at least one given ul class 'someclass' and if I click again and have no elements with class active, remove 'someclass' from the Ul.

How can I do this?

Upvotes: 1

Views: 832

Answers (2)

epascarello
epascarello

Reputation: 207501

There is no need to loop through the elements and add a click to every button. Add one listener.

//listen for click on a button
$('.side-filters', "click", ".filters_list li button", function(){

    //toggle the active class on the button
    var button = $(this).toggleClass("active");

    //see if anything is selected
    var hasSelection = $('.side-filters .filters_list li .active').length > 0;

    //toggle a class on the closest ul based on if anything is selected.
    button.closest("ul").toggleClass("someclass", hasSelection);

});

References:

Upvotes: 1

DaniP
DaniP

Reputation: 38252

You can add this function ()

function someclass () {
   var count = $('.active').length;
   if (count >= 1) {
       $('ul').addClass('clasHere')
   } else {
       $('ul').removeClass('clasHere')
   }
}

Upvotes: 0

Related Questions