
Question:
I have the following code, for enabling a div from toggling between visible and hidden:
function toggle_visibility(id,$this) {
var e = document.getElementById(id);
if(e.style.display == 'block')
{
e.style.display = 'none';
}
else
{
e.style.display = 'block';
}
}
Basically when I click a link that has onclick="toggle_visibility('4s'); within it then the specified div is shown and then when you click again it is hidden.
My problem is when the same code is use for multiple links, and you toggle the visibility of one and then the other, the previous one is still shown. How would I go about only enabling one div to be shown when toggled and then if another is toggled the other is hidden?
Answer1:<a href="http://jsfiddle.net/LdrdG/" rel="nofollow">Here</a> is a generic example using jquery.
<strong>Markup</strong>
<section>
<div id="1">one</div>
<div id="2">two</div>
<div id="3">three</div>
<div id="4">four</div>
</section>
<a href="#1">one</a>
<a href="#2">two</a>
<a href="#3">three</a>
<a href="#4">four</a>
<strong>JS</strong>
var divs = $('section div'),
links = $('a');
links.click(function(){
$(this.hash).toggle().siblings().hide();
return false;
});
Answer2:Keep a global variable for the div which is currently visible and make it invisible when you make any div visible.
var previousVisibleElement;
function toggle_visibility(id,$this) {
var e = document.getElementById(id);
if(e.style.display == 'block')
{
e.style.display = 'none';
}
else
{
if(previousVisibleElement !=null)
previousVisibleElement.style.display='none';
e.style.display = 'block';
previousVisibleElement=e;
}
}
Answer3:if you provide the current script in a jsfiddle people would be able to answer better.
here is a small sample i did using jquery. <a href="http://jsfiddle.net/pramodpv/zzyRx/" rel="nofollow">hide using jquery toggle </a>