I want to call focus() on an input after the widow scrolled. I\'m using the smooth behavior for the scrollTo() method. The problem is the foc
Other answers didn't fully work for me, therefore based on @Fabian von Ellerts answer, I wrote my own solution.
My problems were that :
The element I was scrolling (and all its parents along the hierarchy) always had a offsetTop of 0, so it was not working.
I needed to scroll a nested element.
Using getBoundingClientRect and a container element as reference works :
const smoothScrollTo = (
scrollContainer,
scrolledContent,
offset,
callback
) => {
const fixedOffset = (
scrollContainer.getBoundingClientRect().top + offset
).toFixed()
const onScroll = () => {
if (
scrolledContent.getBoundingClientRect().top.toFixed() ===
fixedOffset
) {
scrollContainer.removeEventListener('scroll', onScroll)
callback()
}
}
scrollContainer.addEventListener('scroll', onScroll)
onScroll()
scrollContainer.scrollTo({
top: offset,
behavior: 'smooth',
})
}