Is there a callback for window.scrollTo?
I wrote a generic function based on the solution of George Abitbol, without overwriting window.onscroll:
/**
* Native scrollTo with callback
* @param offset - offset to scroll to
* @param callback - callback function
*/
function scrollTo(offset, callback) {
const fixedOffset = offset.toFixed();
const onScroll = function () {
if (window.pageYOffset.toFixed() === fixedOffset) {
window.removeEventListener('scroll', onScroll)
callback()
}
}
window.addEventListener('scroll', onScroll)
onScroll()
window.scrollTo({
top: offset,
behavior: 'smooth'
})
}
I found a way to achieve what I want but I think it's a bit hacky, isn't it?
let el = document.getElementById('input')
let elScrollOffset = el.getBoundingClientRect().top
let scrollOffset = window.pageYOffset || document.documentElement.scrollTop
let padding = 12
let target = elScrollOffset + scrollOffset - padding
window.scrollTo({
top: target,
behavior: 'smooth'
})
window.onscroll = e => {
let currentScrollOffset = window.pageYOffset || document.documentElement.scrollTop
// Scroll reach the target
if (currentScrollOffset === target) {
el.focus()
window.onscroll = null // remove listener
}
}