Reputation: 23
Is it possible to use element.scrollIntoView and a "scroll" event listener together?
What i want to do with my code is check if the user scrolled by a certain element, if so, then the page should automatically scroll smoothly to the next section, to do this i tried to use a scroll listener and element.scrollIntoView with behavior smooth, and doing that causes a loop that makes the scroll go really slooow.
I also tried to remove the listener once the function executes, but that doenst work because i need to constantly execute that same function to check the scroll position, testing with console.log made me see that removing the listener makes it execute only once.
Here is the function:
let scrollBox = document.getElementById("scrollbox")
function onScroll(event){
window.removeEventListener("scroll", onScroll);
elementTop = scrollBox.getBoundingClientRect().top;
if(elementTop < 800 && elementTop > 600)
{
divStop.scrollIntoView({block: "end", behavior: "smooth"});
}
event.preventDefault();
};
window.addEventListener("scroll", onScroll)
So, how should i proceed? is there a way to use then both together that i am missing, if not then how can i complete my objective/idea ? Please help.
Upvotes: 2
Views: 2577
Reputation: 477
You could use an IntersectionObserver. Whenever the element you observe is reached, you can then call the scrollIntoView method on the element you want to go to. You can then stop watching the first element if you want to prevent it to loop over and over.
const scrollBox = document.getElementById("scrollbox");
const divStop = document.getElementById("stop");
const scroller = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
divStop.scrollIntoView({ block: "end", behavior: "smooth" });
scroller.unobserve(scrollBox);
}
});
});
scroller.observe(scrollBox);
Upvotes: 3