Created
April 1, 2025 07:59
-
-
Save simeydotme/888dab6fcc16ba88c391145fca7c47da to your computer and use it in GitHub Desktop.
Svelte Intersection Observer Action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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