scrollIntoView Scrolls Anchors Smoothly

Intercept anchor clicks and scroll the matching section into view with smooth behavior, then sync the hash without triggering a page jump.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
const nav = document.querySelector("nav");
const sections = [...document.querySelectorAll("section[id]")];

// 拦截锚点(anchor)默认跳转:scrollIntoView 平滑滚动到目标区块
nav.addEventListener("click", (event) => {
  const link = event.target.closest("a[href^='#']");
  if (!link) return;
  event.preventDefault();
  const target = document.getElementById(link.hash.slice(1));
  if (!target) return;
  target.scrollIntoView({ behavior: "smooth", block: "start" });
  // 同步更新地址栏,不触发页面跳转
  history.replaceState(null, "", link.hash);
});
console.log(`watching ${sections.length} sections`);

How it works

Top-level bindings nav, sections hold the demo state — nothing sits inside a function scope.

Points of care

  • The snippet leans on document — browser-only surfaces a bare Node process cannot provide.
  • The guard !link short-circuits the flow with an early return when its condition holds.

Putting it to use

The demo output is labeled (watching $), so every printed line maps back to its originating operation.

Core lines

const sections = [...document.querySelectorAll("section[id]")];

Interactive Tools for This Topic

FAQ

Does scrollIntoView Scrolls Anchors Smoothly run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.