Search code examples
javascripthtmlanchorbookmarks

javascript call inside a bookmark


wondering if it is possible to have a javascript call inside a html bookmark like:

<a href="bookmark">Go down</a>
.
.
.
<a name="down" href="javascript:alert('movedhere')">

so when visitor clicks on "Go down" the alert message appears but also when url="/#bookmark" then again the function is called.


Solution

  • It's neither scalable nor elegant but it would work if you checked the fragment of the current page when the page loads:

    <script>
    function myCallback()
    {
        alert('movedhere');
    }
    </script>
    
    <a href="#down" onclick="myCallback()">Go down</a>
    .
    .
    .
    <a name="down">
    
    <script>
    var frag = window.location.hash;
    if (frag === '#down')
    {
        myCallback();
    }
    </script>
    

    https://developer.mozilla.org/en/window.location#Properties