SyntaxStudy
Sign Up
jQuery Intermediate 4 min read

Scroll Spy Navigation

Scroll Spy

Highlight the active nav link as sections scroll into view — common in documentation and landing pages.

Example
const sections = $("section[id]");
const $navLinks = $(".sidebar-nav a");
$(window).on("scroll.spy", $.throttle(100, function() {
  const scrollPos = $(this).scrollTop() + 100;
  sections.each(function() {
    const top = $(this).offset().top;
    const bot = top + $(this).outerHeight();
    if (scrollPos >= top && scrollPos < bot) {
      $navLinks.removeClass("active");
      $navLinks.filter(`[href="#${this.id}"]`).addClass("active");
    }
  });
}));
Pro Tip

Use IntersectionObserver instead of scroll events for a modern, performant scroll spy implementation.