Show one div but hide another

Hi,

I am using some simple javascript to show and a hide a div


function showHide(d) {

	if (document.getElementById(d).style.display == "none")
	{
	document.getElementById(d).style.display = "block";
	}
	else
	{
	document.getElementById(d).style.display = "none";
	}
}

and then my html is something like this:


<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>blah blah</div>
<div id="content2>blah blah</div>
<div id="content3>blah blah</div>
<div id="content4>blah blah</div>

so when I click on a link I would like to be able to show a div but hide all the others.

For e.g. If content1 is currently displayed and I click on link2, I want to hide content1 and show content2.

I’m sure it’s something simple but I just can’t figure out what I need to do.

Thanks,
Rachel

in js function make a loop. Hide all divs in that loop and then show only that you send as a parameter when call js function

But I have other divisions that should always remain visible. Would this not hide everything?

Thanks.

Only loop through the ones you want to hide/show…

for(x=1; x<totalContents; x++) {
    if(document.getElementById('content'+x).style.display=='block') {
        document.getElementById('content'+x).style.display='none';
    } else {
        document.getElementById('content'+x).style.display='block';
    }
}

Is that copy and pasted directly from your code? If so, you forgot closing quotes around your div id’s…I imagine that could fix the problem. At least, it works for me in FF3 and IE7 (though in IE it tried to block “active content” which referred to javascript; i allowed it and it worked fine).

Thanks, I got it working using this code



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';
} 


Your guidance is much appreciated :slight_smile: