Skip to main

Click Outside Listener

  • typescript
  • event
  • dom
1 min read

Uses composedPath to detect click outside the target element. This works across (open) Shadow DOM too.

const targetEl = document.getElementById("#target-element");

document.addEventListener("click", (event) => {
  if (event.composedPath().includes(targetEl)) {
    // Clicked within targetEl
  } else {
    // Clicked outside targetEl
  }
});