How to scroll an HTML page to a given anchor with JavaScript?

Spread the love

Sometimes, we want to scroll an HTML page to a given anchor with JavaScript.

In this article, we’ll look at how to scroll an HTML page to a given anchor with JavaScript.

How to scroll an HTML page to a given anchor with JavaScript?

To scroll an HTML page to a given anchor with JavaScript, we set the location.hash property.

For instance, we write

const scrollTo = (hash) => {
  location.hash = "#" + hash;
};

to set the location.hash property to "#" concatenated with the hash, which is the ID of the element we’re scrolling to.

Conclusion

To scroll an HTML page to a given anchor with JavaScript, we set the location.hash property.

Leave a Reply

Your email address will not be published.