Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript changing display using hashtag

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>
like image 472
Ellery Avatar asked Jan 01 '26 20:01

Ellery


1 Answers

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

like image 74
andyb Avatar answered Jan 03 '26 09:01

andyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!