Home  >  Article  >  Web Front-end  >  How to Prevent Page Scroll on Link Click with JavaScript?

How to Prevent Page Scroll on Link Click with JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 22:03:29417browse

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();
});

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;
});

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!

Statement:
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