Skip to content
Advertisement

Check for scrollTo to finish

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.

Plunkr example

var x = document.querySelector('.container');
$scope.scrollTo = function() {
  x.scrollTo({
    top: 300 ,
    behavior: 'smooth'
  });
};

 // do something when scrollTo is finished

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.

function isScrollToFinished() {
        const checkIfScrollToIsFinished = setInterval(() => {
            if (positionOfItem === scrollContainer.scrollTop) {
                // do something
                clearInterval(checkIfScrollToIsFinished);
            }
        }, 25);
}

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement