Can element.scrollIntoView and a "scroll" event listener be used simultaneously?
I'm trying to create code that checks if the user has scrolled past a certain element, and if so, automatically scrolls smoothly to the next section. I attempted to achieve this by using a scroll listener along with element.scrollIntoView with behavior set to smooth. However, this approach resulted in a slow scrolling loop.
I also tried removing the listener once the function is executed, but this method didn't work as expected since the function needs to continuously check the scroll position. Testing with console.log revealed that removing the listener causes it to execute only once.
Below is the function:
let scrollBox = document.getElementById("scrollbox")
function onScroll(event){
window.removeEventListener("scroll", onScroll);
const elementTop = scrollBox.getBoundingClientRect().top;
if(elementTop < 800 && elementTop > 600)
{
divStop.scrollIntoView({block: "end", behavior: "smooth"});
}
event.preventDefault();
};
window.addEventListener("scroll", onScroll)
What steps should I take next? Is there a way to effectively use both methods together that I am overlooking? If not, how can I achieve my goal/idea successfully? Any help would be appreciated.