Detect if an element is in the viewport using the Intersection Observer API.
Try it in the Svelte REPL.
yarn add -D svelte-intersection-observer
# OR
npm i -D svelte-intersection-observer
<script>
import IntersectionObserver from "svelte-intersection-observer";
let element;
let intersecting;
</script>
<header class:intersecting>
{intersecting ? 'Element is in view' : 'Element is not in view'}
</header>
<IntersectionObserver {element} bind:intersecting>
<div bind:this={element}>Hello world</div>
</IntersectionObserver>
The "intersect" event is dispatched only if the observed element is intersecting the viewport.
<IntersectionObserver
{element}
on:intersect="{(e) => {
console.log(e.detail); // IntersectionObserverEntry
}}"
>
<div bind:this={element}>Hello world</div>
</IntersectionObserver>
Prop name | Description | Value |
---|---|---|
element | Element observed for intersection | HTMLElement |
root | Containing element | null or HTMLElement (default: null ) |
rootMargin | Margin offset of the containing element | string (default: "0px" ) |
threshold | Percentage of element visibility to trigger an event | number between 0 and 1 (default: 0 ) |
entry | Observed element metadata | IntersectionObserverEntry |
once | If true , the observed element will be unobserved upon intersect |
boolean (default: false ) |
intersecting | true if the observed element is intersecting the viewport |
boolean (default: false ) |
observer | IntersectionObserver instance | IntersectionObserver |
- on:observe: fired when an intersection change occurs (type
IntersectionObserverEntry
) - on:intersect: fired when an intersection change occurs and the element is intersecting (type
IntersectionObserverEntry
)
Svelte version 3.31.0 or greater is required to use this module with TypeScript.