I'm creating this section of a website where images would slide into view when in the viewport. I just learned about intersection observer and tried to implement it, and it works fine.
The only problem now is that I want it to observe only once, such that the elements stay in place even after scrolling past but it's not working
The issue is that outside the toggleSectionImageMobile function, observer is no longer defined, so I can't access it. And I don't want to redefine it again.
useEffect(() => {
const toggleSectionImageLg = () => {
// Code for larger screens
};
let observer;
const toggleSectionImageMobile = () => {
const callback = (entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("show");
} else {
entry.target.classList.remove("show");
}
});
};
const options = {
root: null,
threshold: 0.8,
};
observer = new IntersectionObserver(callback, options);
const targets = document.querySelectorAll(".feature-img-mobile");
targets.forEach((target) => observer.observe(target));
};
if (window.innerWidth > 900) {
window.addEventListener("scroll", toggleSectionImageLg);
return () => {
window.removeEventListener("scroll", toggleSectionImageLg);
};
} else {
toggleSectionImageMobile();
return () => {
if (observer) {
const targets = document.querySelectorAll(".feature-img-mobile");
targets.forEach((target) => observer.unobserve(target));
}
};
}
}, []);
I tried declaring the observer variable outside using let, but still nothing.
I've also tried moving the unobserve function into the toggleSectionImageMobile, but still didn't work