Sometimes, we want to make an anchor link go some pixels above where it’s linked to with JavaScript.
In this article, we’ll look at how to make an anchor link go some pixels above where it’s linked to with JavaScript.
How to make an anchor link go some pixels above where it’s linked to with JavaScript?
To make an anchor link go some pixels above where it’s linked to with JavaScript, we can use the scrollTo
method.
For instance, we write
window.addEventListener("hashchange", () => {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
to listen to the hashchange
event which is triggered when the hash part of the current URL changes.
In it, we call scrollTo
to scroll to the current location after the hash changed.
Conclusion
To make an anchor link go some pixels above where it’s linked to with JavaScript, we can use the scrollTo
method.