@svelte-put/intersect GitHub

svelte action that wraps for IntersectionObserver

@svelte-put/intersect @svelte-put/intersect @svelte-put/intersect @svelte-put/intersect changelog

Acknowledgement

This package employs svelte action strategy. If you are looking for a declarative & component-based solution, check out metonym's implementation .

Installation

terminal

npm install --save-dev @svelte-put/intersect

Quick start

quick start

<script lang="ts">
  import { intersect, type IntersectDetail } from '@svelte-put/intersect';
  function onIntersect(e: CustomEvent<IntersectDetail>) {
    const { observer, entries, direction } = e.detail;
    console.log('the observer itself', observer);
    console.log('scrolling direction:', direction);
    console.log('intersecting:', entries[0]?.isIntersecting ? 'entering' : 'leaving');
  }
</script>

<div use:intersect on:intersect={onIntersect} />

Initialization Options

intersect take an object parameter that supports all options in IntersectionObserver constructor ( root, rootMargin, threshold, ), and an additional enabled property for enabling/disabling the action.

initialization

<script>
  import { intersect } from '@svelte-put/intersect';
  let root;
</script>

<main bind:this={root}>
  <section
    use:intersect={{
      enabled: true,
      root,
      rootMargin: '100px 0px 50px 0px',
      threshold: [0.2, 0.5, 1],
    }}
  />
</main>

Events

on:intersect

Essentially the same as callback as one passed to the IntersectionObserver constructor, but through the CustomEvent API

intersect will attempt to detect the scrolling direction by keeping record of boundingClientRect. This is available through the direction property.

Example

Scroll down / up to see effect

on:intersect - example source

on:intersectonce

Same interface as on:intersect, but will only fire once on the first intersection.

On possible use case is for fading-in animation on scroll, like in the example below.

Example

Scroll down!

on:intersectonce - example source

intersect observer - ron swanson approves

Happy observing intersection! 👨‍💻

Edit this page on GitHub