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