How do you implement smooth scrolling for anchor links using CSS and JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you implement smooth scrolling for anchor links using CSS and JavaScript?

message-square
0

To implement smooth scrolling for anchor links (<a href="#section">), combine CSS scroll-behavior: smooth and scroll-margin-top (to account for fixed/sticky headers) with JavaScript event delegation and Element.scrollIntoView({ behavior, block }) when you need programmatic control, focus management for accessibility, or reduced-motion compliance (prefers-reduced-motion: reduce). Relying on CSS alone can leave keyboard/screen-reader focus behind or ignore user reduced-motion preferences unless paired with thoughtful handling.


1. CSS Smooth Scrolling and Sticky Header Offset (scroll-margin-top)

Set scroll-behavior: smooth on html (or a specific scroll container) and add scroll-margin-top on target headings/sections so fixed navigation bars do not cover section titles when scrolled into view:

/* CSS snippet: smooth scrolling + clearance below a 72px fixed header */
html {
  scroll-behavior: smooth;
}

[id] {
  scroll-margin-top: 72px;
}

@media (prefers-reduced-motion: reduce) {
  html {
    scroll-behavior: auto;
  }
}
  • Use scroll-margin-top instead of padding hacks: Keeps layout spacing clean while reserving visual breathing room above anchored targets.
  • Respect prefers-reduced-motion: reduce: Users who experience motion sensitivity expect instant jumps rather than animated scrolling.

2. JavaScript Anchor Interception with Accessibility and Reduced-Motion Support

Use event delegation on document (or a navigation container) to intercept same-page hash links (href^="#"), validate the target element, choose "instant" vs. "smooth" based on matchMedia("(prefers-reduced-motion: reduce)"), and move keyboard focus cleanly to the target without causing an unwanted page jump:

// Smoothly scroll to an anchor target while respecting reduced motion & keyboard focus
function bindSmoothAnchorLinks(root = document) {
  if (!root || typeof root.addEventListener !== "function") {
    throw new TypeError("Expected root to be a DOM Document or Element with addEventListener.");
  }

  const handleClick = (event) => {
    if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
      return;
    }

    const anchor = event.target instanceof Element ? event.target.closest('a[href^="#"]') : null;
    if (!anchor) {
      return;
    }

    const rawHash = anchor.getAttribute("href") ?? "";
    const targetId = rawHash.slice(1);
    if (!targetId) {
      return;
    }

    let targetElement = null;
    try {
      targetElement = document.getElementById(decodeURIComponent(targetId));
    } catch {
      targetElement = document.getElementById(targetId);
    }

    if (!targetElement) {
      return;
    }

    event.preventDefault();

    const prefersReducedMotion =
      typeof window.matchMedia === "function" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;

    try {
      targetElement.scrollIntoView({
        behavior: prefersReducedMotion ? "auto" : "smooth",
        block: "start"
      });

      if (!targetElement.hasAttribute("tabindex")) {
        targetElement.setAttribute("tabindex", "-1");
      }
      targetElement.focus({ preventScroll: true });

      if (typeof history !== "undefined" && typeof history.pushState === "function") {
        history.pushState(null, "", `#${targetId}`);
      }
    } catch (error) {
      console.error(`Smooth scroll failed for "#${targetId}": ${error.message}`);
      window.location.hash = `#${targetId}`;
    }
  };

  root.addEventListener("click", handleClick);
  return () => root.removeEventListener("click", handleClick);
}

// Example usage:
// const cleanupSmoothScroll = bindSmoothAnchorLinks(document);
  • Pass { preventScroll: true } to .focus(): Prevents .focus() on a non-focusable target (tabindex="-1") from interrupting or overriding scrollIntoView().
  • Ignore modified clicks (Ctrl/Cmd/middle-click): Lets users open anchor links in a new tab naturally.

3. Scrolling Within a Custom Scroll Container Safely

When scrolling inside a nested scrollable container (overflow-y: auto / scroll) rather than the window viewport, compute the relative offset or call container.scrollTo({ top, behavior }) instead of scrolling the outer document:

// Smoothly scroll a specific container to a child element with optional top offset
function scrollElementIntoContainer(container, target, offsetPx = 0) {
  if (!(container instanceof Element) || !(target instanceof Element)) {
    throw new TypeError("Expected both container and target to be DOM Elements.");
  }
  if (typeof offsetPx !== "number" || !Number.isFinite(offsetPx)) {
    throw new TypeError("Expected offsetPx to be a finite number.");
  }

  const prefersReducedMotion =
    typeof window.matchMedia === "function" &&
    window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  const containerRect = container.getBoundingClientRect();
  const targetRect = target.getBoundingClientRect();
  const nextTop = container.scrollTop + (targetRect.top - containerRect.top) - offsetPx;

  try {
    container.scrollTo({
      top: Math.max(0, nextTop),
      behavior: prefersReducedMotion ? "auto" : "smooth"
    });
  } catch (error) {
    container.scrollTop = Math.max(0, nextTop);
    console.warn(`Fallback instant scroll used: ${error.message}`);
  }
}

// Example usage:
// scrollElementIntoContainer(document.querySelector("#docs-pane"), document.querySelector("#section-3"), 16);
  • Avoid scrollIntoView() on nested containers if it scrolls ancestors unexpectedly: Using container.scrollTo(...) keeps movement strictly inside the intended scroll pane.
  • Check element existence before scrolling: Missing target IDs fail silently or throw if dereferenced without a null check.