I have an element that is scrollable. I also have a function that scrolls to a specific position. I would like to call a function when the scrollTo is finished.
JavaScript
x
10
10
1
var x = document.querySelector('.container');
2
$scope.scrollTo = function() {
3
x.scrollTo({
4
top: 300 ,
5
behavior: 'smooth'
6
});
7
};
8
9
// do something when scrollTo is finished
10
Advertisement
Answer
By checking the position of the element I am scrolling to and comparing that to the current scroll position of the container you can see when the scrolling action is finished.
JavaScript
1
9
1
function isScrollToFinished() {
2
const checkIfScrollToIsFinished = setInterval(() => {
3
if (positionOfItem === scrollContainer.scrollTop) {
4
// do something
5
clearInterval(checkIfScrollToIsFinished);
6
}
7
}, 25);
8
}
9
The interval checks if the position of the scroll container is equal to the position of the element I’m scrolling to. Then do a action and clear the interval.