Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Link to and toggle div on other page.

    I have the following page with collapsed/hidden (by default) div tags:
    Code:
    <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:
    Code:
    <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

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,733
    Thanks
    80
    Thanked 4,516 Times in 4,480 Posts
    Not hard.

    At the bottom of the page, just before </body>, put this:
    Code:
    <script type="text/javascript">
    if ( location.hash.length > 1 )
    {
        toggleDiv( location.hash.substring(1) );
    }
    </script>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    silmarilj (07-02-2012)

  • #3
    New to the CF scene
    Join Date
    Jun 2012
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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?
    Code:
    <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 :-)
    Last edited by silmarilj; 07-02-2012 at 07:26 PM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •