MCPcopy Create free account
hub / github.com/ampproject/amphtml / useClickOutside

Function useClickOutside

src/preact/hooks/useClickOutside.tsx:10–33  ·  view source on GitHub ↗
(
  elementRef: RefObject<HTMLElement>,
  callback: (ev: MouseEvent) => void
)

Source from the content-addressed store, hash-verified

8 * Works with any combination of Light DOM and Shadow DOM.
9 */
10export function useClickOutside(
11 elementRef: RefObject<HTMLElement>,
12 callback: (ev: MouseEvent) => void
13) {
14 const cb = useEvent(callback);
15
16 useEffect(() => {
17 if (!elementRef.current) {
18 return;
19 }
20
21 const handler = (ev: MouseEvent) => {
22 const element = elementRef.current;
23 if (element && !shadowContains(element, ev.target as Element)) {
24 cb(ev);
25 }
26 };
27 const document = elementRef.current.ownerDocument;
28 document.addEventListener('click', handler, {capture: true});
29 return () => {
30 document.removeEventListener('click', handler, {capture: true});
31 };
32 }, [elementRef, cb]);
33}
34
35/**
36 * Same as Element.contains, except it traverses shadow DOM too.

Callers 1

BentoMegaMenuWithRefFunction · 0.90

Calls 3

useEventFunction · 0.85
removeEventListenerMethod · 0.80
addEventListenerMethod · 0.45

Tested by

no test coverage detected