A simple rule-based approach to tracking element viewability.
Try it in the Svelte REPL.
yarn add -D @svelte-plugins/viewable
# or with NPM
npm i -D @svelte-plugins/viewable
<script>
import Viewable from "@svelte-plugins/viewable";
const immediately = (definition) => {
console.log('element has crossed the viewport');
};
const dwell = (definition) => {
console.log('50% of the element was visible for at least 4 consecutive seconds');
};
const rules = {
// do something when the element enters the viewport
immediately: { duration: 0, percentage: 0, fn: immediately },
// do something when 50% of the element is visible for 4 seconds (consecutively)
dwell: { duration: 4, percentage: 50, fn },
};
let element;
</script>
<Viewable {rules} {element}>
<div bind:this={element}>Hello World</div>
</Viewable>