Reputation: 23
I have two divs and I want to show only one of the divs based on clicking a list element. I wrote the following code. Its not working. Its always showing me Div1 (or whichever one I make visible initially). How do I make it show me appropriate div? Thank you.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
function showPane(paneId) {
document.getElementById("Div1").style.display="none";
document.getElementById("Div2").style.display="none";
document.getElementById(paneId).style.display="block";
}
</script>
</head>
<body onload="showPane('Div1');">
<ul id="nav">
<li><a href="" onclick="showPane('Div1')">Div1</a></li>
<li><a href="" onclick="showPane('Div2')">Div2</a></li>
</ul>
<div id="Div1">
<h3>This is Div1</h3>
</div>
<div id="Div2">
<h3>This is Div2</h3>
</div>
</body>
</html>
Upvotes: 2
Views: 143
Reputation: 517
You can add "return false" to the onclick to prevent it from following the link:
onclick="showPane('Div1'); return false;"
Upvotes: 1
Reputation: 1634
You need to set # to href. Otherwise the page will get reload
<ul id="nav">
<li><a href="#" onclick="showPane('Div1')">Div1</a></li>
<li><a href="#" onclick="showPane('Div2')">Div2</a></li>
</ul>
Upvotes: 0
Reputation:
Just another variation to the already answered
<li><a href="javascript:showPane('Div1');" >Div1</a></li>
<li><a href="javascript:showPane('Div2');">Div2</a></li>
Upvotes: 1
Reputation: 5257
Because the list items are <a>
which redirect you to the same page. than the body onload shows div1.
Add href="javascript:;"
to the <a>
to prevent this.
Or add the event
arg to the function:
<a href="" onclick="showPane(event,'Div1')">
and in the function:
function showPane(event,paneId) {
event.preventDefault();
//rest of code
}
To prevent the default behavior of the MouseClick Event. http://codepen.io/yardenst/pen/cKqIy
Upvotes: 3
Reputation: 7138
It shows you div2 but then it quickly gets over-written by div1 again.(Try clicking the link for div2 very fast.) This is because when you click the link, the entire page re-loads and the onload event gets triggered and shows you Div1. To overcome this, use buttons or some other element which does not cause a page reload.
Upvotes: 0
Reputation: 19573
here is your problem:
<li><a href=""
make those to be
<li><a href="#"
when you do
href=""
that is actually a link to the current page you are on, which triggers the body onload and activates div1 right after the click event.
Upvotes: 0