0Pricing
Sveltejs Academy · Lesson

Practical Actions: clickOutside tooltip autofocus

Build real-world reusable actions for common UI patterns.

clickOutside Action

Detect clicks outside an element to close menus and dropdowns.

function clickOutside(node, cb) {
  function handler(e) { if (!node.contains(e.target)) cb(); }
  document.addEventListener("click", handler, true);
  return { destroy() { document.removeEventListener("click", handler, true); } };
}

Use clickOutside

Pass a callback that runs when the user clicks outside.

<div use:clickOutside={() => open = false}>

All lessons in this course

  1. use: Directive Syntax
  2. Action Parameters and Updates
  3. The destroy() Cleanup Function
  4. Practical Actions: clickOutside tooltip autofocus
← Back to Sveltejs Academy