feat(smoothScroll): add util to smoothly scroll to the id after anchor click
This commit is contained in:
32
src/shared/lib/utils/smoothScroll/smoothScroll.ts
Normal file
32
src/shared/lib/utils/smoothScroll/smoothScroll.ts
Normal file
@@ -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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user