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.