I was trying to move user to a certain position (which a HTMLElement with a given id is) when user click a button. So far I have tried using hashtag directly and using hash tag and add a listener listen to the router change in useEffect, and send user to the element if hashtag is detected and that element is not in the view port. They are not working at most of the time. I added a while loop to keep triggering the function, which results bringing user to the element after 20+ calls in 7-8 seconds. That is just annoying.
Does anyone successfully make the hashtag works? How can that be done?
What I have tried so far: hashtag link: failed hashtag link with a slash before the hashtag: failed, can't see a difference function moving user to the location: failed, but the function itself is successfully triggered
What I am observing at the moment:
Related code:
function isInViewport(el: HTMLElement) {
const rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
useEffect(() => {
const path = router.asPath;
if (path && path.includes('/#')) {
const sectionName = path.replace('/#', '');
const ele = document.getElementById(sectionName);
if (ele) {
const interval = setInterval(() => {
if (!isInViewport(ele)) {
console.log('triggered');
setTimeout(() => {
ele.scrollIntoView({ behavior: "smooth" })
}, 2000)
}
else {
clearInterval(interval);
}
}, 2000);
}
}
}, [router.asPath]);