useClickAnyWhere

Hook to catch the click on any part of the site

Related hooks

Inspired on:

Visual example

site title
domain.tld

Code base

import { useEventListener } from "@dimaslz/svelteuse"

type Handler = (event: MouseEvent) => void;

export function useClickAnyWhere(handler: Handler): () => void {
	return useEventListener<MouseEvent>("click", (event) => {
		handler(event);
	});
}

Code example

<!-- javascript -->
<script lang="ts">
	import { onMount } from "svelte";
	import { useClickAnyWhere } from "@dimaslz/svelteuse";

	const someCallback = () => {
		console.log("click anywhere!");
	};

	onMount(() => {
		const eventClickAnyWhere = useClickAnyWhere(someCallback);

		return () => {
			eventClickAnyWhere();
		}
	})
</script>

<!-- html -->
<div>
	content
</div>