What I am trying to achieve is to check the collision between two elements. I got a page h1 tag, and want to check if it turns invisible because it's hidden behind the very top header when scrolling. The header is defined in my layout.tsx file with a component, which contains a simple header-tag.
With the current attempt I get the visible message when refreshing the page (and it's not colliding by the start), then scrolling so it hides and I get the invisible message. After these two console messages, it doesn't work at all anymore.
This is what I currently got:
const titleElement = useSignal<HTMLHeadingElement | undefined>(undefined);
const visibility = useSignal<boolean>(false); // Track previous visibility
useVisibleTask$(() => {
const options = {
root: null
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
const isVisible = entry.intersectionRatio > 0 && entry.boundingClientRect.top >= 0;
// Check if visibility state has changed
if (isVisible !== visibility.value) {
visibility.value = isVisible;
if (isVisible) {
console.log("Title element is fully visible.");
// Perform actions when the title element is fully visible
} else {
console.log("Title element is fully invisible.");
// Perform actions when the title element is fully invisible
}
}
});
}, options);
if (titleElement.value) {
observer.observe(titleElement.value);
return () => {
observer.disconnect();
};
}
})
return (
<div class="p-16">
<h1 ref={titleElement} class="text-[4rem] text-indigo-300 font-bold text-center">Basics of nutrition</h1>
</div>
)
