When an intersection observer is added to an element, it triggers the handler function when scrolled past a specific point. However, if the element is scrolled past that point using a button click, the handler does not get triggered.
Is there a way to manually fire the handler when scrolling by using scrollTo or scrollIntoView?
const container = document.getElementById("container");
const hello = document.getElementById("hello");
const button = document.getElementById("button");
const options = {
rootMargin: "-100px 0px 0px 0px",
threshold: 1
}
const handleIntersect = entries => {
entries.forEach((entry) => {
console.log("handleIntersect")
});
};
const observer = new IntersectionObserver(handleIntersect, options);
observer.observe(hello);
button.addEventListener("click", () => {
container.scrollTo({
top: 120
});
})
body {
margin: 0;
}
#container {
background-color: #ddd;
height: 400px;
overflow-y: auto;
}
.inner-container {
height: 100px;
border-bottom: 1px solid #bbb;
position: absolute;
top: 0;
left: 0;
right: 0;
text-align: right;
}
#button {
margin: 40px;
font-size: 20px;
}
#hello {
display: inline-block;
padding: 20px 40px;
background-color: blue;
color: white;
margin-top: 150px;
margin-bottom: 500px;
}
<div id="container">
<div class="inner-container">
<button id="button">Scroll</button>
</div>
<div id="hello">Hello</div>
</div>