Files
frontend-svelte/src/shared/lib/utils/smoothScroll/smoothScroll.ts

44 lines
1.1 KiB
TypeScript

/**
* Svelte action for smooth anchor scrolling
*
* Intercepts anchor link clicks to smoothly scroll to the target element
* instead of jumping instantly. Updates URL hash without causing scroll.
*
* @example
* ```svelte
* <a href="#section" use:smoothScroll>Go to Section</a>
* <div id="section">Section Content</div>
* ```
*
* @param node - The anchor element to attach to
* @returns Action object with destroy method
*/
export function smoothScroll(node: HTMLAnchorElement) {
const handleClick = (event: MouseEvent) => {
event.preventDefault();
const hash = node.getAttribute('href');
if (!hash || hash === '#') return;
const targetElement = document.querySelector(hash);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
// Update URL hash without triggering scroll
history.pushState(null, '', hash);
}
};
node.addEventListener('click', handleClick);
return {
destroy() {
node.removeEventListener('click', handleClick);
},
};
}