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
Linda HamiltonOriginal
2024-12-10 08:57:11305browse

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

jQuery Method for Older Browsers:

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

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

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

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

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

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!

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