Sometimes, we want to stop a web page from scrolling to the top when a link is clicked that triggers JavaScript.
In this article, we’ll look at how to stop a web page from scrolling to the top when a link is clicked that triggers JavaScript.
How to stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call preventDefault
.
For instance, we write
document.getElementById("#ma_link").addEventListener("click", (e) => {
e.preventDefault();
doSomething();
});
to select the link with getElementById
.
Then we call addEventListener
to add a click listener.
In it, we call preventDefault
to stop the= default behavior of scrolling to the top.
Conclusion
To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call preventDefault
.