Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Hide all other divs

I've a number of divs that are only visible after clicking a link. How to close all open divs so that only the clicked one is visible?
I'm using this .js:

    function showhide(id){
        if (document.getElementById) {
        var divid = document.getElementById(id);
        divid.style.display = (divid.style.display=='block'?'none':'block');
        } }

        <a href="javascript:void(null)" onclick="showhide('features');">features</a>
<a href="javascript:void(null)" onclick="showhide('design');">design</a>
<a href="javascript:void(null)" onclick="showhide('create');">create</a>

Thanks Uli

like image 744
Uli Avatar asked Dec 28 '11 12:12

Uli


1 Answers

One way is to add a class and seek the elements based on that to hide them (as shown in other answers)

An alternative is to store the state of the elements in an object and use that to identify the open ones that need closing..

var divState = {}; // we store the status in this object
function showhide(id) {
    if (document.getElementById) {
        var divid = document.getElementById(id);

        divState[id] = (divState[id]) ? false : true; // initialize / invert status (true is visible and false is closed)
        //close others
        for (var div in divState){
            if (divState[div] && div != id){ // ignore closed ones and the current
                document.getElementById(div).style.display = 'none'; // hide
                divState[div] = false; // reset status
            }
        }
        divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
    }
}

Demo at http://jsfiddle.net/gaby/LfzYc/

like image 199
Gabriele Petrioli Avatar answered Oct 06 '22 23:10

Gabriele Petrioli