Home >Web Front-end >JS Tutorial >How to Prevent Page Scrolling to Top When Clicking JavaScript Links?

How to Prevent Page Scrolling to Top When Clicking JavaScript Links?

DDD
DDDOriginal
2024-10-26 09:00:03364browse

 How to Prevent Page Scrolling to Top When Clicking JavaScript Links?

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!

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