Anekdotos
Anekdotos

Reputation: 3

Load different DIV content based on what's appended to the URL

I feel there is such an easy answer to this, but my google-fu is failing me. What I currently have are several links that once clicked, change the HTML content in a DIV.

<a href="#new" onclick="document.getElementById('body').innerHTML
= '<p>NEW</p>';">NEW!</a>

But I want to be able to link to this content. Is there anyway to link to this by going to a URL such as www.blahblah.com/index.html#new so it auto-loads the new HTML code?

Forgive me if I'm an idiot... I'm fairly new to javascript.

Upvotes: 0

Views: 1468

Answers (2)

offex
offex

Reputation: 1885

You can use window.location.hash to see what the hash is on the URL and show the correct DIV based on that. Assuming all your divs are on the page, once you know the div you want to show you would do something like this:

document.getElementById(idOfDivToShow).style.display='block';

Small example:

<html>
  <head>
    <script type="text/javascript">
      function loadDiv() {
        if(window.location.hash == '#div1')
          document.getElementById('div1').style.display = "block";
        else if(window.location.hash == '#div2')
          document.getElementById('div2').style.display = "block";
      }
    </script>
  </head>
  <body onload="loadDiv()">
    <div style="display:none" id="div1">div1</div>
    <div style="display:none" id="div2">div2</div>
  </body>
</html>

Upvotes: 2

user203715
user203715

Reputation:

If you use jQuery, Mootools, or Prototype you could use history.js which allows you to set up states with specific content depending on the hash.

Upvotes: 1

Related Questions