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 focus
method cut the smooth behavior. The solution is to call the focus
function just after the scroll end.
But I can't find any doc or threads speaking about how to detect the end of scrollTo
method.
let el = document.getElementById('input') let elScrollOffset = el.getBoundingClientRect().top let scrollOffset = window.pageYOffset || document.documentElement.scrollTop let padding = 12 window.scrollTo({ top: elScrollOffset + scrollOffset - padding, behavior: 'smooth' }) // wait for the end of scrolling and then el.focus()
Any ideas?
Now you can use just window. scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.
scrollTo only works when the scroll behavior is set on html . If you have set overflow: scroll on some container inside of the DOM, then that need to be accessed. Assign an id to that. For example I have below div container for which I have set overflow: scroll .
Parameters: The scrollTo() method accepts two parameters as described below: x-coord: It is the pixel along the horizontal axis of the document that is displayed in the upper left. It is the required field. y-coord: It is the pixel along the vertical axis of the document that is displayed in the upper left.
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' }) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With