Reputation: 23
I've got the following code that works great! When I click Link 1, the DIV content appears. When I click it again, it disappears. If I click Link 1 again, the DIV content appears again. If I click Link 2 this time, the content appears along with Link 1 content. I want Link 1 to disappear if another DIV link is clicked. I don't want to have to turn that content off before turning another one on. How do I make a DIV disappear after another one is clicked?
Javascript:
function show(ele) {
var srcElement = document.getElementById(ele);
if(srcElement != null) {
if(srcElement.style.display == "block") {
srcElement.style.display= 'none';
}
else {
srcElement.style.display='block';
}
}
return false;
}
DIV:
<a href="#" onclick="show('link1')">FIRST LINK</a>
<a href="#" onclick="show('link2')">SECOND LINK</a>
<div id="link1" style="display:none">
<p>Link 1 Content Displayed</p>
</div>
<div id="link2" style="display:none">
<p>Link 2 Content Displayed</p>
</div>
I don't want to change the way I'm doing this, I feel like there's a simple solution, I just can't figure it out! Any help is appreciated.
Upvotes: 0
Views: 4710
Reputation: 4156
Another, better answer would be to use jQuery, because it lets you write better javascript without having to worry about whether IE is going to break.
include this tag in the head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
Javascript:
function show( elem )
{
$('.dynamic_link').hide();
$('#'+elem).show();
}
HTML:
<a href="#" onclick="show('link1')">FIRST LINK</a>
<a href="#" onclick="show('link2')">SECOND LINK</a>
<div id="link1" class="dynamic_link" style="display:none">
<p>Link 1 Content Displayed</p>
</div>
<div id="link2" class="dynamic_link" style="display:none">
<p>Link 2 Content Displayed</p>
</div>
Upvotes: 3
Reputation: 4156
Javascript (modified):
function show(ele) {
var links = ['link1','link2'];
var srcElement = document.getElementById(ele);
var doShow = true;
if(srcElement != null && srcElement.style.display == "block")
doShow = false;
for( var i = 0; i < links.length; ++i ) {
var otherElement = document.getElementById(links[i]);
if( otherElement != null )
otherElement.style.display = 'none';
}
if( doShow )
srcElement.style.display='block';
return false;
}
working example: http://jsfiddle.net/vDKmA/
Upvotes: 1