...

View Full Version : Link to and toggle div on other page.



silmarilj
06-27-2012, 08:00 PM
I have the following page with collapsed/hidden (by default) div tags:

<html>
<head>
<title>Test</title>
<script language="javascript">
function toggleDiv(divid){
if(document.getElementById(divid).style.display == 'none'){
document.getElementById(divid).style.display = 'block';
}else{
document.getElementById(divid).style.display = 'none';
}
}
</script>
</head>
<body>
<h1>Test</h1>
<a name="SEC1" href="javascript:;" onmousedown="toggleDiv('divSEC1');"><p><b>Section 1</b></p></a>
<div id="divSEC1" style="display:none">
Content for section 1.
</div>
<a name="SEC2" href="javascript:;" onmousedown="toggleDiv('divSEC2');"><p><b>Section 2</b></p></a>
<div id="divSEC2" style="display:none">
Content for section 2.
</div>
</body>
</html>
It seems to work as intended. Page loads with desired content hidden until I click on the section heading.

My question is how to link to a specific section from another page, and have that div toggle to show the desired content.
I could link to the section simply enough:

<a href="test.html#SEC2">Section 2</a>
But that wouldn't expand the desired content.

Hoping there is a reasonably simple way to accomplish.
Danke

Old Pedant
06-27-2012, 10:21 PM
Not hard.

At the bottom of the page, just before </body>, put this:


<script type="text/javascript">
if ( location.hash.length > 1 )
{
toggleDiv( location.hash.substring(1) );
}
</script>

silmarilj
07-02-2012, 07:57 PM
Thanks for the reply, but I wasn't able to get this working. Do I need to modify any of my existing code first?

Does my link method need to be different?

<a href="test.html#SEC2">Section 2</a>

Edit: Nevermind, I just realized my div id's needed to be the same as the anchor names. Works great now, thank you so much :-)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum