Skip to content

Instantly share code, notes, and snippets.

@simeydotme
Created April 1, 2025 07:59
Show Gist options
  • Save simeydotme/888dab6fcc16ba88c391145fca7c47da to your computer and use it in GitHub Desktop.
Save simeydotme/888dab6fcc16ba88c391145fca7c47da to your computer and use it in GitHub Desktop.
Svelte Intersection Observer Action
import type { Action } from 'svelte/action';
interface IntersectionObserverParams {
threshold?: number;
root?: Element | Document | null;
rootMargin?: string;
visibilityToggle?: boolean;
}
export const observe: Action<HTMLElement, IntersectionObserverParams> = (node, params = {}) => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
if (params.visibilityToggle) {
node.style.visibility = 'visible';
node.classList.remove('opacity-0');
}
node.dispatchEvent(new CustomEvent('enterview'));
} else {
if (params.visibilityToggle) {
node.style.visibility = 'hidden';
node.classList.add('opacity-0');
}
node.dispatchEvent(new CustomEvent('exitview'));
}
});
},
{
threshold: params.threshold ?? 0.1,
root: params.root ?? null,
rootMargin: params.rootMargin ?? '0px',
}
);
observer.observe(node);
return {
destroy() {
observer.disconnect();
},
update(newParams) {
observer.disconnect();
observer.observe(node);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment