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.
Code
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
!linkshort-circuits the flow with an earlyreturnwhen 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
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.