...

View Full Version : Hide/show: need to display one div by default



mattetc
12-03-2012, 09:39 PM
I found the following code that works great EXCEPT that it shows all divs upon page load. I need to have 'content1' display and the other divs be hidden when the page loads. After clicking any of the showHide links it behaves as expected. What code do I need to add/change/remove?



<script>
function showHide(d)
{
var onediv = document.getElementById(d);
var divs=['content1','content2','content3','content4'];
for (var i=0;i<divs.length;i++)
{
if (onediv != document.getElementById(divs[i]))
{
document.getElementById(divs[i]).style.display='none';
}
}
onediv.style.display = 'block';
}
</script>

<a href="javascript:showHide('content1');">link1</a>
<a href="javascript:showHide('content2');">link2</a>
<a href="javascript:showHide('content3');">link3</a>
<a href="javascript:showHide('content4');">link4</a>

<div id="content1">Default content</div>
<div id="content2">2nd item</div>
<div id="content3">3rd item</div>
<div id="content4">4th item</div>

Old Pedant
12-03-2012, 10:54 PM
HTML/CSS question. Nothing really to do with JS.

But let's simplify the JS and modernize the HTML while we are at it, at least a bit:



<style type="text/css">
#content1 { display: block; }
#content2, #content3, #content4 { display: none; }
</style>

<script>
function showHide(d)
{
for (var i = 1; i < 99999; ++i )
{
var div = document.getElementById("content" + i );
if ( div == null ) break; // no more to do
div.style.display = ( d == i ) ? "block" : "none";
}
return false; // to cancel the action of the <a> tag!
}
</script>

<a href="#" onclick="return showHide(1);">link1</a>
<a href="#" onclick="return showHide(2);">link2</a>
<a href="#" onclick="return showHide(3);">link3</a>
<a href="#" onclick="return showHide(4);">link4</a>

<div id="content1">Default content</div>
<div id="content2">2nd item</div>
<div id="content3">3rd item</div>
<div id="content4">4th item</div>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum