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

How Can I Implement Smooth Scrolling for Anchor Links?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 22:42:18929browse

How Can I Implement Smooth Scrolling for Anchor Links?

Achieving Smooth Scrolling with Anchor Links

Incorporating hyperlinks to FAQs within a help section is a common approach to guide users to specific information. While anchor links enable page scrolling to the target location, achieving a smooth scrolling experience can enhance user interaction.

Native and jQuery-based Solutions

The latest versions of browsers now support a native solution for smooth anchor scrolling.

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

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

For wider browser compatibility, jQuery offers an alternative technique:

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

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

Additionally, jQuery handles cases where the target element doesn't have an ID.

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

    return false;
});

Performance Optimization

Caching the $('html, body') selector can significantly improve performance.

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

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

    return false;
});

Updating URL

If updating the URL upon scrolling is desired, it can be achieved within the animation 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?. 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