From f01299f3d13d788c9af464a2908862ac74380ba8 Mon Sep 17 00:00:00 2001 From: Ilia Mashkov Date: Tue, 10 Feb 2026 21:15:39 +0300 Subject: [PATCH] feat(smoothScroll): add util to smoothly scroll to the id after anchor click --- .../lib/utils/smoothScroll/smoothScroll.ts | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/shared/lib/utils/smoothScroll/smoothScroll.ts diff --git a/src/shared/lib/utils/smoothScroll/smoothScroll.ts b/src/shared/lib/utils/smoothScroll/smoothScroll.ts new file mode 100644 index 0000000..9f3c616 --- /dev/null +++ b/src/shared/lib/utils/smoothScroll/smoothScroll.ts @@ -0,0 +1,32 @@ +/** + * Smoothly scrolls to the target element when an anchor element is clicked. + * @param node - The anchor element to listen for clicks on. + */ +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 jumping + history.pushState(null, '', hash); + } + }; + + node.addEventListener('click', handleClick); + + return { + destroy() { + node.removeEventListener('click', handleClick); + }, + }; +}