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

To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call the preventDefault method.

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 to it.

And we call e.preventDefault in the click listener to stop the scrolling.

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 *