I have a show/hide script that I am using for a menu. When I click a main link it brings up a list below it. I was wondering if there is a way to alter it a bit so that when I click the link it opens but when I click the next one it closes the other one instead of leaving them all open unless you click it again to close.
Here is my script:
<script type="text/javascript">
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<a href="#" onclick="toggle_visibility('list1');">
<p>List One</p>
</a>
<div id="list1" style="display:none;">
<ul>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
</ul>
</div>
I would add one more function to hide all the lists but one current:
http://jsfiddle.net/q2E5e/
Suppose this is your code:
Change it to this:
And make your JavaScript this:
Here's a JSFiddle.
Instead of using plain JavaScript for this, I suggest you use jQuery.
Here's how I would do it in jQuery: