I have a page which demonstrates the smooth scroll to an id with below details:
Use Case:
- The tabs should be fixed when window scroll is greater than 300px.
- When particular tab is clicked, page must scroll to the desired section without body scroll.
I found this below code in some of the stackoverflow thread to animate to a particular id, but it seems to make whole body scroll on every tab click.
animate(elem, style, unit, from, to, time, prop) {
if (!elem) {
return;
}
const start = new Date().getTime(),
timer = setInterval(function() {
const step = Math.min(1, (new Date().getTime() - start) / time);
if (prop) {
elem[style] = from + step * (to - from) + unit;
} else {
elem.style[style] = from + step * (to - from) + unit;
}
if (step === 1) {
clearInterval(timer);
}
}, 25);
if (prop) {
elem[style] = from + unit;
} else {
elem.style[style] = from + unit;
}
}
Please check the attached stackblitz code for the reference https://stackblitz.com/edit/angular-u1dfnc.
Issue: On clicking section-1 tab for the first time it doesn't scroll perfectly but when I click the same tab for the second time it scrolls properly.
Can anyone help me in achieving proper scrolling to an id on tab click without making the body to scroll.
PS: I also followed Smooth link scrolling not on whole body, but certain div thread, but this was in jQuery. I am trying to achieve with only javascript/typescript.