Skip to content

Latest commit

 

History

History
90 lines (63 loc) · 2.35 KB

is-in-viewport.md

File metadata and controls

90 lines (63 loc) · 2.35 KB
title description category
IsInViewport
Track if an element is visible within the current viewport.
Elements
<script> import Demo from '$lib/components/demos/is-in-viewport.svelte'; </script>

IsInViewport uses the useIntersectionObserver utility to track if an element is visible within the current viewport.

It accepts an element or getter that returns an element and an optional options object that aligns with the useIntersectionObserver utility options.

Demo

Usage

Basic Usage

<script lang="ts">
	import { IsInViewport } from "runed";

	let targetNode = $state<HTMLElement>()!;
	const inViewport = new IsInViewport(() => targetNode);
</script>

<p bind:this={targetNode}>Target node</p>

<p>Target node in viewport: {inViewport.current}</p>

One-time Detection

The once option automatically stops observing after the first intersection. This is useful for one-time animations or loading content when it becomes visible:

<script lang="ts">
	import { IsInViewport } from "runed";

	let targetNode = $state<HTMLElement>()!;
	const inViewport = new IsInViewport(() => targetNode, {
		once: true
	});
</script>

<div bind:this={targetNode} class="transition" class="transition-opacity {hasBeenSeen ? 'opacity-100' : 'opacity-0'}">
	I'll fade in once when first visible, then stop observing
</div>

Observer Controls

The IsInViewport class provides methods to control the underlying intersection observer. See useIntersectionObserver for more information.

Type Definition

import { type UseIntersectionObserverOptions } from "runed";
export type IsInViewportOptions = UseIntersectionObserverOptions;

export declare class IsInViewport {
	constructor(node: MaybeGetter<HTMLElement | null | undefined>, options?: IsInViewportOptions);

	/** Current viewport intersection state */
	get current(): boolean;

	/** Stop observing permanently */
	stop(): void;

	/** Pause observation temporarily */
	pause(): void;

	/** Resume observation after pausing */
	resume(): void;

	/** Whether the observer is currently active */
	get isActive(): boolean;
}