Home > Web Front-end > JS Tutorial > body text

How to Prevent Page Scrolling to Top After JavaScript-Triggered Link Clicks?

Linda Hamilton
Release: 2024-10-26 05:25:02
Original
573 people have browsed it

 How to Prevent Page Scrolling to Top After JavaScript-Triggered Link Clicks?

How to Prevent Page Scrolling to Top on JavaScript-Triggered Link Clicks

Many developers encounter an issue where web pages scroll to the top when a link is clicked that activates JavaScript. This can be frustrating if the desired action is to perform a non-navigation operation.

To resolve this, you need to prevent the default action of the click event (navigating to the link target) from happening. There are two common methods to achieve this:

Option 1: event.preventDefault()

In this approach, you call the .preventDefault() method of the event object passed to your event handler. This halts the browser's native navigation behavior. Here's an example using jQuery:

<code class="javascript">$('#ma_link').click(function($e) {
    $e.preventDefault();
    // Perform your JavaScript action here
});</code>
Copy after login

Option 2: return false

Alternatively, returning false from a jQuery event handler automatically triggers both event.stopPropagation() and event.preventDefault(). This prevents both propagation and default navigation:

<code class="javascript">$('#ma_link').click(function(e) {
     // Perform your JavaScript action here
     return false;
});</code>
Copy after login

For non-jQuery DOM events, you can also use this approach on modern browsers, as it's part of the HTML 5 specification. However, for older browsers, it's recommended to call .preventDefault() explicitly for maximum compatibility.

The above is the detailed content of How to Prevent Page Scrolling to Top After JavaScript-Triggered Link Clicks?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!