html – anchor jumping by using javascript

html – anchor jumping by using javascript

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

Here is a lazier way to do that:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = #+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Dont like hashes. Changing it back.
}

This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}‚Äč

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. Its not complicated at all.)

I think it is much more simple solution:

window.location = (+window.location).replace(/#[A-Za-z0-9_]*$/,)+#myAnchor

This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.

html – anchor jumping by using javascript

Not enough rep for a comment.

The getElementById() based method in the selected answer wont work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you dont have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace(# + hash) }

Leave a Reply

Your email address will not be published.