Hooks

useClickOutside

A Svelte action that detects clicks outside an element. Useful for closing dropdowns, modals, popups, and any UI that should dismiss when clicking elsewhere.

Basic Usage

Click outside the colored box to trigger the handler. Usage: use:useClickOutside={{ handler }}

Click outside this box
Click outside the box below
<script lang="ts">
  import { Badge } from 'sv5ui';
  import { useClickOutside, toast } from 'sv5ui';

  let clickCount = $state(0);

  function handleClickOutside() {
    clickCount += 1;
    toast('Clicked outside the box!');
  }
</script>

<!-- Svelte action: spread on the element -->
<div use:useClickOutside={{ handler: handleClickOutside }}
  class="rounded-lg border-2 border-dashed border-primary/40 bg-primary/10 p-6 text-center">
  <p>Click outside this box</p>
  <Badge label={String(clickCount)} variant="soft" color="primary" size="xs" />
</div>

Enable / Disable

Toggle the enabled option to control whether outside clicks are detected.

Detection active - click outside
Click outside the box below
<script lang="ts">
  import { Switch, FormField } from 'sv5ui';
  import { useClickOutside, toast } from 'sv5ui';

  let enabled = $state(true);

  function handleClick() {
    toast('Outside click detected!');
  }
</script>

<FormField label="Enabled" size="sm">
  <Switch bind:checked={enabled} size="sm" />
</FormField>

<div use:useClickOutside={{ handler: handleClick, enabled }}
  class="rounded-lg border-2 border-dashed p-6 text-center">
  Detection is {enabled ? 'ON' : 'OFF'}
</div>

Options

Passed as an object to the Svelte action.

OptionTypeDefault
handler(event: MouseEvent) => void-
enabledbooleantrue