Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a callback for window.scrollTo?

Tags:

javascript

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?

like image 608
Existe Deja Avatar asked Sep 12 '18 10:09

Existe Deja


People also ask

How do I make Windows scroll smooth?

Now you can use just window. scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

How do I use scrollTo in Windows react?

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 .

How does window scrollTo work?

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.


1 Answers

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'     }) } 
like image 152
Fabian von Ellerts Avatar answered Sep 18 '22 22:09

Fabian von Ellerts