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

How to Prevent Page Scroll on Link Click with JavaScript?

Mary-Kate Olsen
Release: 2024-10-26 22:03:29
Original
415 people have browsed it

How to Prevent Page Scroll on Link Click with JavaScript?

Preventing Page Scroll on Link Click with JavaScript

When utilizing JavaScript or jQuery to enhance link behavior, it's common to encounter an issue where clicking a link triggers the page to scroll to the top. If you wish to prevent this behavior, you have a few options.

Firstly, consider the event.preventDefault() method. By invoking this method on the event object passed to your handler, you effectively disable the default action (such as navigating to the link target). This works whether you use jQuery's $e.preventDefault() or the native Event.preventDefault() in the DOM.

For instance, the following jQuery code prevents scrolling:

$('#ma_link').click(function($e) {
    $e.preventDefault();
    doSomething();
});
Copy after login

Another option is to leverage jQuery's return false; behavior. By returning false from an event handler, both event.stopPropagation() and event.preventDefault() are automatically called. Therefore, you can use the following approach:

$('#ma_link').click(function(e) {
     doSomething();
     return false;
});
Copy after login

Additionally, if you prefer raw DOM events, returning false on modern browsers will prevent the default link behavior. However, explicitly calling .preventDefault() is recommended for maximum compatibility with older browsers, as the HTML5 spec did not initially include this behavior.

The above is the detailed content of How to Prevent Page Scroll on Link Click with JavaScript?. 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!