Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Jump to anchor function

I use this script to check if an anchor is within the URL. If found the showscroll function get called. Only thing isn't working is the jump to the called anchor. I'm new to JS - what is wrong with the function?

In the HTML page:

   <script type="text/javascript">
    <!--
    function checkurl(){
    if (window.location.href.match(/\#more/))
    {
    showscroll('more');
    }
    if (window.location.href.match(/\#tab2/))
    {
    showscroll('tab2');
    }

    }
    //-->
    </script>

    </head>                   

    <body onload="checkurl()"> 

.JS

function showscroll(id){
    if (document.getElementById) {
    var divid = document.getElementById(id);
    divid.style.display = divid.style.display='block';
    // NOT WORKING:
 window.location.href = "#"+id;
//
    return false;
} }

Edit: I can't use "scroll into view".

like image 958
Tom Avatar asked May 13 '26 01:05

Tom


1 Answers

Instead of

window.location.href.match(/\#more/)

you can just do

window.location.hash == '#more'

and instead of assigning to the fragment, you can use the scrollIntoView method as described at https://developer.mozilla.org/en/DOM/element.scrollIntoView

Summary

The scrollIntoView() method scrolls the element into view.

Syntax

element.scrollIntoView(alignWithTop);

alignWithTop Optional

If true, the scrolled element is aligned with the top of the scroll area. If false, it is aligned with the bottom.
Note: By default, the element is scrolled to align with the top of the scroll area.

like image 128
Mike Samuel Avatar answered May 14 '26 14:05

Mike Samuel