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. http://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>
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:see Alternative to <body onload="init ();">