Anchor Jumping By Using Javascript


Answer :

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);   //Don't 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. It's 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.


Not enough rep for a comment.

The getElementById() based method in the selected answer won't 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 don't 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) } 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?