Reputation: 1022
I have 3 Divs on top of each other and 3 links to toggle its visibility.
By default all Divs are set to display:none
and the sript below works for each corresponding div but need to toggle the state of the other, for example:
Link 1 = Shows Div1 (or vice versa) when I click on Link 2 I need to Show Div2 and Hide Div1,Div3. If I click on Link3 = Show Div3 and Hide Div1,Div2 if they are visible and so on... In other words, Show 1 div at a time.
How can I do it? here is what I have so far.
Links
<a href="#" onclick="toggle_visibility('Soft');"></a>
<a href="#" onclick="toggle_visibility('Broch');"></a>
<a href="#" onclick="toggle_visibility('tut');"></a>
DIVs
<div id="Soft" style="display: none;">.....</div>
<div id="broch" style="display: none;">.....</div>
<div id="tut" style="display: none;">.....</div>
Javascript
function toggle_visibility(Soft) {
var soft = document.getElementById(Soft);
if(soft.style.display == 'block')
soft.style.display = 'none';
else
soft.style.display = 'block';
}
function toggle_visibility(Broch) {
var e = document.getElementById(Broch);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
function toggle_visibility(tut) {
var e = document.getElementById(tut);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
Upvotes: 1
Views: 6521
Reputation: 29951
You might want to store the state on a variable. Try this:
var divs = ["Soft", "broch", "tut"];
var visibleDivId = null;
function toggleVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
Working example: http://jsbin.com/Ipezadu/1/
Upvotes: 1
Reputation: 7356
This is extremely easy with JQuery. JSFiddle
<a href="#" data-div="div1">Toggle DIV 1</a>
<a href="#" data-div="div2">Toggle DIV 2</a>
<a href="#" data-div="div3">Toggle DIV 3</a>
<div id="div1">DIV 1</div>
<div id="div2" style="display: none">DIV 2</div>
<div id="div3">DIV 3</div>
$('a').on('click', function() {
$('div[id="' + $(this).data('div') + '"]').toggle();
});
Upvotes: 0