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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With