Categories
JavaScript Answers

How to make anchor link go some pixels above where it’s linked to with JavaScript?

Spread the love

To make anchor link go some pixels above where it’s linked to with JavaScript, we call scrollTo when the URL hash changes.

For instance, we write

window.addEventListener("hashchange", () => {
  window.scrollTo(window.scrollX, window.scrollY - 100);
});

to listen for the hashchange event on the window with addEventListener.

In the hashchange listener, we call scrollTo to scroll to the scroll position of the window.

window.scrollX and window.scrollY has the x and y coordinates of the scroll position.

The hashchange event is emitted, when the URL part after the # sign changes.

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 *