in JavaScript how can I detect ending of a scrollTo function to execute something after ?
- User
in JavaScript how can I detect ending of a scrollTo function to execute something after ?
- Assistant
You can detect the end of scrollTo function by using the
onscrollevent and checking if thescrollTopproperty has reached its maximum value (i.e., the end of the scrolling). Here is an example:const element = document.getElementById('my-element'); const scrollEnd = element.scrollHeight - element.clientHeight; // calculate the max scroll value element.onscroll = function() { if (element.scrollTop === scrollEnd) { // the scrollTo function has ended, execute something here console.log('Scroll ended!'); } }; element.scrollTo({ top: scrollEnd, behavior: 'smooth' }); // start the scrollTo functionIn this example, we attach a callback function to the
onscrollevent of the element we want to scroll. The callback function is executed whenever the user scrolls the element or when thescrollTofunction changes the scroll position. Inside the callback function, we check if thescrollTopproperty has reached its maximum value (scrollEnd). If so, we know that the scrollTo function has ended, and we can execute something else. - User
no I mean scrolling can be without reaching top or bottom, from a value to a value. I am thinking something like promise etc.
- Assistant
In that case, you can use the
scrollevent to detect when the scrolling has stopped. You can create a promise that resolves when thescrollevent is triggered with theisScrollingflag set tofalse. Here's an example:function scrollTo(element, to, duration) { return new Promise((resolve) => { const start = element.scrollTop; const change = to - start; const increment = 20; let currentTime = 0; function animateScroll() { currentTime += increment; const val = Math.easeInOutQuad(currentTime, start, change, duration); element.scrollTop = val; if (currentTime < duration) { setTimeout(animateScroll, increment); } else { resolve(); } } animateScroll(); element.addEventListener('scroll', function handleScroll() { if (!this.isScrolling) { this.removeEventListener('scroll', handleScroll); resolve(); } }); }); } // usage scrollTo(document.documentElement, 500, 1000).then(() => { console.log('Scrolling has ended!'); }); // easing function Math.easeInOutQuad = function (t, b, c, d) { t /= d / 2; if (t < 1) return (c / 2) * t * t + b; t--; return (-c / 2) * (t * (t - 2) - 1) + b; };