Categories
JavaScript Answers

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

Spread the love

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 define the scrollTo function.

In it, we set location.hash to the selector for the ID for the element we want to scroll to.

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 *