@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

Action Usage Notice

As with any svelte action , intersect should be use with element and not component.

use:action is an element directive

<-- correct usage-->
<div use:intersect />

<-- incorrect usage-->
<Component use: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

Typescript Support

Ambient types for custom events should be available automatically where intersect is imported.

automatically typed - example source

If the above is not working, fall back to this:

src/app.d.ts - fallback typescript support

API Reference

The best documentation is no documentation!

It is recommended to utilize editor intellisense & explore in-code documentation while using the package (and use typescript if possible 😉) .

See the extracted API Reference on github.

API extraction is powered by @microsoft/api-extractor and @microsoft/api-documenter ).

intersect observer - ron swanson approves

Happy observing intersection! 👨‍💻

Edit this page on GitHub