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

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

DDD
Release: 2024-10-26 09:00:03
Original
268 people have browsed it

 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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
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!