Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-1
rated 0 times [  4] [ 5]  / answers: 1 / hits: 17529  / 13 Years ago, wed, december 28, 2011, 12:00:00

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


More From » html

 Answers
19

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/


[#88342] Monday, December 26, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackelyn

Total Points: 303
Total Questions: 103
Total Answers: 102

Location: Turks and Caicos Islands
Member since Sun, Mar 7, 2021
3 Years ago
jackelyn questions
Thu, Apr 8, 21, 00:00, 3 Years ago
Sun, Feb 28, 21, 00:00, 3 Years ago
Mon, May 25, 20, 00:00, 4 Years ago
Thu, Apr 30, 20, 00:00, 4 Years ago
;