3

I'm very new to JS and have a problem with something that looks very simple. I am trying to make a code so that if the page loads with a # at the end of the url, eg. www.example.com#hashtag, then a div will display, if it doesn't have a # the div wont display.

My Code:

JS:

<script type="text/javascript">
if(window.location.hash) {
document.getElementById("displaydiv").style.display = "block"; 
}
</script>

HTML:

<div id="displaydiv" style="display: none; height: 100px; width: 100px; 
background-color: red;"></div>
Ellery
  • 179
  • 1
  • 9

3 Answers3

2

The code is correct, but the <script> is executing too early, before the <div> is rendered, so I suspect you are getting a JavaScript error in the browser. Did you check the browser console?

Moving the <script> after the <div> will fix it but it might be wise to put the code into a function and call it after the page has loaded, for example:

<script type="text/javascript">
    function init() {
        if (window.location.hash) {
            document.getElementById("displaydiv").style.display = "block"; 
        }
    }

    window.onload = init;
</script>

see Alternative to <body onload="init ();">

Community
  • 1
  • 1
andyb
  • 43,435
  • 12
  • 121
  • 150
0

This will get the Hash (#displayDiv) and show that particular div...

<script type="text/javascript">
  var hasher = window.location.hash;

  if(hasher.indexOf('displaydiv') > -1) {
    document.getElementById("displaydiv").style.display = "block"; 
  } else if (hasher.indexOf('anotherDiv') > -1) {
    document.getElementById("anotherDiv").style.display = "block";
  }
</script>

<div id="displaydiv" style="display: none; height: 100px; width: 100px; background-color: red;"></div>
Barrie Reader
  • 10,647
  • 11
  • 71
  • 139
0

How about a simple CSS solution using the :target selector:

*:target {
  display: block;
}
Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62