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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-18 15:42:11487browse

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

Smooth Scrolling with Anchor Links

When utilizing anchor links to direct users to specific sections of a webpage, a smooth scrolling experience can enhance user accessibility and engagement. jQuery offers built-in features to achieve this effect.

jQuery Technique

To initiate smooth scrolling using jQuery, employ the following code:

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

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

Native Approach (Modern Browsers)

Modern browsers now support native smooth scrolling for anchor links. Implement this behavior with the following code:

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

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

Additional Considerations

No ID Attribute: If the target element lacks an ID attribute but is identified by name, use this code:

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

    return false;
});

Performance Optimization: Cache the document root selector to improve performance:

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

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

    return false;
});

URL Update: To update the URL during scrolling, use this callback:

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 jQuery and Native 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