SyntaxStudy
Sign Up
jQuery Beginner 4 min read

Smooth Scroll to Anchor

Smooth Scroll

Animate the page scroll to anchor targets with jQuery for browsers that do not support CSS scroll-behavior.

Example
$("a[href^=\"#\"]").on("click", function(e) {
  const target = $(this.hash);
  if (target.length) {
    e.preventDefault();
    const offset = 80; // sticky header height
    $("html, body").animate({
      scrollTop: target.offset().top - offset
    }, 600, "swing", function() {
      window.location.hash = target.attr("id");
      target.attr("tabindex", "-1").focus();
    });
  }
});
/* CSS alternative */
/* html { scroll-behavior: smooth; scroll-padding-top: 80px; } */
Pro Tip

Move focus to the target after scroll — keyboard users need the focus, not just the visual scroll.