Categories
JavaScript Answers

How to add anchor jumping by using JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *