clickOutside
A Svelte action that fires a callback when clicking outside an element.
Usage
How It Works
- Uses
mousedownevent for better UX (fires before focus changes) - Checks if click target is outside the element using
contains() - Ignores clicks with
defaultPrevented - Listens on document level with capture phase
Common Patterns
Dropdown Menu
Modal Dialog
Search with Suggestions
API
clickOutside(node, callback)
node HTMLElement The element to watch (provided by Svelte)
callback () => void Function called when clicking outside
Returns
update(newCallback) Update the callback function
destroy() Cleanup event listener
Tips
- Wrap parent element - Apply to the container, not individual items
- Combine with escapeKey - For complete modal/dropdown accessibility
- Use with portals - Works correctly even with portaled content