Click outside
clickOutside is a Svelte attachment. It runs its handler on a pointerdown outside the element it is attached to.
<div {@attach clickOutside(() => (isOpen = false))}>...</div>The wrapper holds both the toggle button and the panel, so a press on the button is inside and only a press elsewhere closes the panel.
Code
<script lang="ts"> import { clickOutside } from "@viamrobotics/prime-ui";
let isOpen = $state(false);</script>
<div class="not-content"> <div class="flex items-start gap-3" {@attach clickOutside(() => (isOpen = false))}> <button type="button" class="button" aria-expanded={isOpen} onclick={() => (isOpen = !isOpen)} > Toggle panel </button> {#if isOpen} <div class="border-medium bg-medium rounded-sm border p-3 text-sm"> Press anywhere outside this panel and its button to close it. </div> {/if} </div></div>With a popover
Section titled “With a popover”A Popover or Menu renders its content in a portal, outside the panel’s DOM subtree. Content that the element’s trigger links through aria-controls counts as inside, so a press in the popover does not close the panel.
Code
<script lang="ts"> import { Popover, clickOutside } from "@viamrobotics/prime-ui";
let isOpen = $state(false);</script>
<div class="not-content"> <div class="flex items-start gap-3" {@attach clickOutside(() => (isOpen = false))}> <button type="button" class="button" aria-expanded={isOpen} onclick={() => (isOpen = !isOpen)} > Toggle panel </button> {#if isOpen} <div class="border-medium bg-medium flex flex-col gap-2 rounded-sm border p-3 text-sm"> <p>The popover renders in a portal, and pressing in it keeps the panel open.</p> <Popover> <Popover.Trigger class="button button-outline">Options</Popover.Trigger> <Popover.Content aria-label="Options"> <p class="text-sm">Press here, then outside the panel.</p> </Popover.Content> </Popover> </div> {/if} </div></div>Exclude
Section titled “Exclude”exclude receives the press target and returns true for a target that may be pressed without counting as outside. It adds to the element’s own subtree and its aria-controls content, and does not replace them.
| Argument | Type | Description |
|---|---|---|
handler |
(event: PointerEvent) => void |
Runs on a pointerdown outside the element. |
options |
{ exclude?: (target: HTMLElement) => boolean } |
exclude marks targets that count as inside, beyond the subtree and aria-controls content. |