"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Short & Direct: How to prevent the page from scrolling to the top after clicking a JavaScript link? Why does my page jump to the top after clicking?

Short & Direct: How to prevent the page from scrolling to the top after clicking a JavaScript link? Why does my page jump to the top after clicking?

Posted on 2025-04-16
Browse:137

Here are some question-based titles for your provided article, focusing on the problem of page scrolling to the top after a JavaScript link click:

Short & Direct:

* How to Stop Page Scrolling to Top on JavaScript Link Click?
* Why Does My Page Jump to T

How to Prevent Page Scrolling to Top on JavaScript Link Click:

When triggering a JavaScript event from a linked element, such as an anchor tag, it's common to encounter the issue of the page jumping to the top after the event fires.

Solution:

To prevent this unwanted behavior, it's necessary to suppress the default action of the click event. This can be achieved using two methods:

1. event.preventDefault():

By calling the .preventDefault() method on the event object passed to the event handler, you can prevent the default behavior of navigating to the link target.

Example (jQuery):

$('#my-link').click(function(event) {
  event.preventDefault();
  // Your JavaScript code here
});

Example (DOM):

document.getElementById('my-link').addEventListener('click', function(event) {
  event.preventDefault();
  // Your JavaScript code here
});

2. return false:

In jQuery, returning false from an event handler will automatically call both .stopPropagation() and .preventDefault() methods.

Example (jQuery):

$('#my-link').click(function(event) {
  // Your JavaScript code here
  return false;
});

If using raw DOM events, it's recommended to explicitly call .preventDefault() for maximum compatibility with older browsers. Refer to the documentation on event.preventDefault() vs. return false for details.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3