Skip to content

Commit

Permalink
support dynamically changing the rootMargin (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
dysfunc authored Apr 23, 2021
1 parent 60b78cb commit 76b5a4a
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions src/IntersectionObserver.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@
const dispatch = createEventDispatcher();
let prevRootMargin = null;
let prevElement = null;
onMount(() => {
const initialize = () => {
observer = new IntersectionObserver(
(entries) => {
entries.forEach((_entry) => {
Expand All @@ -61,6 +63,10 @@
},
{ root, rootMargin, threshold }
);
}
onMount(() => {
initialize();
return () => {
if (observer) observer.disconnect();
Expand All @@ -74,7 +80,7 @@
if (entry.isIntersecting) {
dispatch("intersect", entry);
if (once) observer.unobserve(entry.target);
if (once) observer.unobserve(element);
}
}
Expand All @@ -86,6 +92,14 @@
if (prevElement !== null) observer.unobserve(prevElement);
prevElement = element;
}
if (prevRootMargin && rootMargin !== prevRootMargin) {
observer.disconnect();
prevElement = null;
initialize();
}
prevRootMargin = rootMargin;
});
</script>

Expand Down

0 comments on commit 76b5a4a

Please sign in to comment.