Preventing Page Scrolling to Top When Clicking JavaScript-Triggered Links
When clicking a link associated with a JavaScript event, such as:
<a href="#">My Link</a>
the page may scroll to the top unintendedly. To prevent this behavior while maintaining the link's functionality, consider the following solutions:
Option 1: event.preventDefault()
Utilize the event object's .preventDefault() method to prevent the browser from performing its default action of navigating to the link.
<code class="javascript">$('#ma_link').click(function($e) { $e.preventDefault(); doSomething(); }); document.getElementById('#ma_link').addEventListener('click', function (e) { e.preventDefault(); doSomething(); })</code>
Option 2: return false;
In jQuery, returning false from an event handler automatically calls event.stopPropagation() and event.preventDefault().
<code class="javascript">$('#ma_link').click(function(e) { doSomething(); return false; });</code>
For more browser compatibility, explicitly call .preventDefault() when using raw DOM events.
The above is the detailed content of How to Prevent Page Scrolling to Top When Clicking JavaScript Links?. For more information, please follow other related articles on the PHP Chinese website!