Home > Web Front-end > JS Tutorial > How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?

How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?

Linda Hamilton
Release: 2024-12-10 08:57:11
Original
304 people have browsed it

How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?

Creating Smooth Scrolling for Anchor Links

Smooth scrolling enhances user experience when using anchor links to navigate within a page. This article provides two approaches to achieve this effect: a native method compatible with modern browsers and a jQuery implementation for broader support.

Native Method for Modern Browsers:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', (e) => {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});
Copy after login

jQuery Method for Older Browsers:

$(document).on('click', 'a[href^="#"]', function (event) {
    event.preventDefault();

    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top
    }, 500);
});
Copy after login

Note: For elements without an ID, this variation should be used:

$('a[href^="#"]').click(function () {
    $('html, body').animate({
        scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
    }, 500);

    return false;
});
Copy after login

Performance Optimization:

To improve performance, cache the $('html, body') selector:

var $root = $('html, body');

$('a[href^="#"]').click(function () {
    $root.animate({
        scrollTop: $( $.attr(this, 'href') ).offset().top
    }, 500);

    return false;
});
Copy after login

Updating URL:

For cases where you want the URL to reflect the current section, use this variation:

var $root = $('html, body');

$('a[href^="#"]').click(function() {
    var href = $.attr(this, 'href');

    $root.animate({
        scrollTop: $(href).offset().top
    }, 500, function () {
        window.location.hash = href;
    });

    return false;
});
Copy after login

The above is the detailed content of How Can I Implement Smooth Scrolling for Anchor Links Using JavaScript and jQuery?. 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