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

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

<script language="javascript">
function toggleDiv(divid){
if(document.getElementById(divid).style.display == 'none'){
document.getElementById(divid).style.display = 'block';
document.getElementById(divid).style.display = 'none';
<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.
<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.
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.

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) );

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 :-)