Categories
JavaScript Answers

How to stop anchor element click from making page jump to top of page with JavaScript?

Spread the love

Sometimes, we want to stop anchor element click from making page jump to top of page with JavaScript.

In this article, we’ll look at how to stop anchor element click from making page jump to top of page with JavaScript.

How to stop anchor element click from making page jump to top of page with JavaScript?

To stop anchor element click from making page jump to top of page with JavaScript, we call preventDefault in the anchor element’s click handler.

For instance, we write:

<a href='#'>click me</a>

to add the anchor element.

Then we write:

const a = document.querySelector('a')
a.onclick = (e) => {
  e.preventDefault()
}

to select the anchor element with querySelectorAll.

Then we set a.onclick to a function that calls e.preventDefault to stop the page from moving up when we click it.

Conclusion

To stop anchor element click from making page jump to top of page with JavaScript, we call preventDefault in the anchor element’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 *