eventListenerStore

Use EventListener with simplicity. Supports Window, Element and Document and custom events with almost the same parameters as the native addEventListener options. See examples below.

Demo

Check console for logs.

Usage

<script lang="ts">
import { eventListenerStore } from '$lib';
import { onMount } from 'svelte';

let buttonRef: HTMLButtonElement;
let documentRef: Document;

const onScroll = (event: Event) => {
  console.log("window scrolled!", event);
};

const onClick = (event: Event) => {
  console.log("button clicked!", event);
};

const onVisibilityChange = (event: Event) => {
  console.log("doc visibility changed!", {
    isVisible: !document.hidden,
    event,
  });
};

onMount(() => {
  // example with window based event
  eventListenerStore('scroll', onScroll)

  // example with document based event
  eventListenerStore('visibilitychange', onVisibilityChange, documentRef)

  eventListenerStore('click', onClick, buttonRef)
});
</script>

<button bind:this={buttonRef}>Click me</button>