user2032775
user2032775

Reputation:

Toggling classes or visibility

I'm using this code for toggling visibility of a class, but once hidden, elements are not becoming visible again. Look at my demo. Click on "1", and then click on "All" for hidinh and showing all items.

var toggle_visibility = (function() {
    function toggle(cl) {
        var els = document.getElementsByClassName(cl);
        for(var i=0; i<els.length; ++i) {
            var s = els[i].style;
            s.display = s.display==='none' ? 'inline-block' : 'none';
        };
    }
    return function(cl) {
        if (cl instanceof Array) {
            for(var i=0; i<cl.length; ++i) {
                toggle(cl[i]);
            }
        }
        else {
            toggle(cl);
        }
    };
})();

Upvotes: 1

Views: 97

Answers (2)

bowlturner
bowlturner

Reputation: 2016

After looking at the code and playing with the fiddle, it's pretty obvious what is going on. the Show/Hide all button is changing the ul class to display or not, which affects all the li tags. if you set the none at the ul it turns off the whole list, if you click on 1,2 or 3 the list items get display turned on and off individually. Click 1, click all, click 3, click all. see what's happening? you are using visibility at different levels.

Click 1

<ul class="item-all">
    <li class="iconMap-3 item-01" style="display:none;"/>1
    <li class="iconMap-3 item-02"/>2
    <li class="iconMap-3 item-03"/>3
</ul>

Click All

 <ul class="item-all" style="display:none;">
    <li class="iconMap-3 item-01" style="display:none;"/>1
    <li class="iconMap-3 item-02"/>2
    <li class="iconMap-3 item-03"/>3
</ul>

Click 3

<ul class="item-all" style="display:none;">
    <li class="iconMap-3 item-01" style="display:none;"/>1
    <li class="iconMap-3 item-02"/>2
    <li class="iconMap-3 item-03"  style="display:none;"/>3
</ul>

Click all

<ul class="item-all">
    <li class="iconMap-3 item-01" style="display:none;"/>1
    <li class="iconMap-3 item-02"/>2
    <li class="iconMap-3 item-03"  style="display:none;"/>3
</ul>

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

The problem is that item-all is a container of item-01, item-02 and item-03. If you want to show, let's say, item-01 when item-all is hidden, you'll have to make it visible again.

An option according your code and HTML would be using

toggle_visibility('iconMap-3');

instead of

toggle_visibility('item-all');

DEMO

Upvotes: 1

Related Questions