Skip to content Skip to sidebar Skip to footer

How Do I "toggle All", And Also Toggle Specific Classes Of Elements?

I want to toggle the visibility of classes of list items and also toggle the visibility of all the list items. With help of another stack overflow post, I am able to toggle specifi

Solution 1:

I'm not sure if this is exactly what you're trying to do, but it should give you a push in the right direction (at least the direction I'd go). I prefer toggling everything with classes. Something like:

<button class="toggler" data-class="easy">Easy</button>,
<buttonclass="toggler"data-class="fun">Fun</button>,
<buttonclass="toggler"data-class="silly">Silly</button>,
<buttonclass="toggler"data-class="all">Select All</button><ulid="list"><liclass="easy">Bowling</li><liclass="fun">Balooning</li><liclass="fun easy">Boating</li><liclass="silly">Barfing</li><liclass="easy fun">Bafooning</li></ul>

The CSS:

#listli {
    display: none;
}
#list.easyli.easy {
    display: block;
}
#list.funli.fun {
    display: block;
}
#list.sillyli.silly {
    display: block;
}
#list.allli {
    display: block;
}

The JS:

$('.toggler').click(function () {
    var category = $(this).data('class');
    $('#list').toggleClass(category);
});

And a fiddle for reference: http://jsfiddle.net/qLLYj/

Solution 2:

You can explicitly add/remove a class by passing a second, switch, parameter to toggleClass(see here).

So, you can change the state of all the individual switches and list items when clicking the .select_all button.

$('.select_all').click(function () {
    $('.select_all').toggleClass("checked");
    var allChecked = $('.select_all').hasClass("checked");
    switcher = [allChecked, allChecked, allChecked];
    $(".toggler").toggleClass("checked", allChecked);
    $('li').toggleClass("hidden", !allChecked);
});

Some further changes made to get more intuitive behaviour (e.g. if all checked, clicking one of the toggles deselects .select_all as well as itself; checking all individual toggles means .select_all is automatically checked):

$('.toggler').click(function () {
    var x = $(this).hasClass('checked');
    switcher[$(this).data('switch')] = !x;
    $(this).toggleClass("checked");
    $('li').each(function () {
        var cur = $(this);
        cur.addClass('hidden');
        $.each(switcher, function (index, data) {
            if (data && cur.hasClass(classes[index])) {
                cur.removeClass('hidden');
            }
        });
    });

    var allChecked = switcher.indexOf(false) < 0;
    $('.select_all').toggleClass("checked", allChecked);
});

Fiddle: http://jsfiddle.net/ET33B/

Post a Comment for "How Do I "toggle All", And Also Toggle Specific Classes Of Elements?"