Show/hide div's with javascript on a button press (and have all div's hidden first)

Obon picture Obon · Feb 12, 2014 · Viewed 41.3k times · Source

I am new to javascript and I cant seam to hide the div's to start with, I can get the divs to switch between each other any help would be great

<script type="text/javascript">
function show(elementId) { 
 document.getElementById("id1").style.display="none";
 document.getElementById("id2").style.display="none";
 document.getElementById("id3").style.display="none";
 document.getElementById(elementId).style.display="block";
}
</script>


<button type="button" onclick="show('id1');">Button 1</button>
<button type="button" onclick="show('id2');">Button 2</button>
<button type="button" onclick="show('id3');">Button 3</button>

<div id="id1">text 1</div>
<div id="id2">text 2</div>
<div id="id3">text 3</div>

Answer

Emilio Rodriguez picture Emilio Rodriguez · Feb 12, 2014

You can hide all the divs by adding inline styles:

<script type="text/javascript">
function show(elementId) { 
 document.getElementById("id1").style.display="none";
 document.getElementById("id2").style.display="none";
 document.getElementById("id3").style.display="none";
 document.getElementById(elementId).style.display="block";
}
</script>


<button type="button" onclick="show('id1');">Button 1</button>
<button type="button" onclick="show('id2');">Button 2</button>
<button type="button" onclick="show('id3');">Button 3</button>

<div id="id1"  style="display:none">text 1</div>
<div id="id2"  style="display:none">text 2</div>
<div id="id3"  style="display:none">text 3</div>

See it working here: http://jsbin.com/suhok/2/