Categories
JavaScript Answers

How to stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Spread the love

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 in the link’s click handler.

For instance, we write

document.getElementById("#ma_link").addEventListener("click", (e) => {
  e.preventDefault();
  doSomething();
});

to select the link with getElementById.

Then we call addEventListener with 'click' and a click event handler callback.

In the callback, we call e.preventDefault to stop the default behavior of scrolling to the top of the page when the link is clicked.

Conclusion

To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call preventDefault in the link’s click handler.

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 *