onClickOutside

List for clicks outside of an element. Useful for modal or dropdown.

Usage

<script>
  import { writable, onClickOutside } from '@svelte-use/core'

  const target = writable()

  onClickOutside(target, (event) => {
    // do something
  })
</script>

<div bind:this={$target}>Hello World</div>
<div>Outside element</div>

This function uses Event.composedPath() which is NOT supported by IE 11, Edge 18 and below. If you are targeting these browsers, we recommend you to include this code snippet on your project.

Type Declarations

export declare type OnClickOutsideEvents = Pick<
  WindowEventMap,
  | "click"
  | "mousedown"
  | "mouseup"
  | "touchstart"
  | "touchend"
  | "pointerdown"
  | "pointerup"
>
export interface OnClickOutsideOptions<E extends keyof OnClickOutsideEvents>
  extends ConfigurableWindow {
  event?: E
}
/**
 * Listen for clicks outside of an element
 *
 * @see https://svelte-use.vercel.app/core/onClickOutside
 * @param target
 * @param handler
 * @param options
 */
export declare function onClickOutside<
  E extends keyof OnClickOutsideEvents = "pointerdown"
>(
  target: MaybeElementReadable,
  handler: (evt: OnClickOutsideEvents[E]) => void,
  options?: OnClickOutsideOptions<E>
): Fn | undefined

Source

SourceDemoDocs