To add anchor jumping by using JavaScript, we use the scrollTo
method.
For instance, we write
const jump = (h) => {
const top = document.getElementById(h).offsetTop;
window.scrollTo(0, top);
};
to define the jump
function.
In it, we get the element with getElementById
.
And we get the y coordinate of the target element with offsetTop
.
Then we call window.scrollTo
with 0 and top
to scroll to the element.