Skip to content

Instantly share code, notes, and snippets.

@NisugaJ
Created February 26, 2024 21:10
Show Gist options
  • Save NisugaJ/84b6a786dedf5e05615981169ec9ff39 to your computer and use it in GitHub Desktop.
Save NisugaJ/84b6a786dedf5e05615981169ec9ff39 to your computer and use it in GitHub Desktop.
Detect a mouse click event outside of a given node
/**
* Detect outside clicks
* @param node - The node to detect outside clicks. The callback will be executed when outside of this node click is detected
* @param callback - The callback to execute when an outside click is detected
* @param excludes - The ids of the nodes to exclude from the outside click detection
*/
export function outsideClick(
node: Node,
{
callback,
excludes
}: {
callback: () => void
excludes: string[]
}
) {
const handleClick = (event: Event) => {
// Identify whether the clicked node is an excluded node to detect outside clicks
const excludingNodes = excludes.map((id) => document.getElementById(id))
const isAnExcludedNode = excludingNodes.some(
(elem: HTMLElement | null) => elem !== null && elem.contains(event.target as Node)
)
if (
!node.contains(event.target as Node) && // Check if the clicked node is outside the element and its children
!isAnExcludedNode // Check if the clicked node is not an excluded node
) {
callback()
}
}
// Listen for click events on the document
document.addEventListener('click', handleClick, true)
return {
destroy() {
// Remove the event listener when the element is destroyed
document.removeEventListener('click', handleClick, true)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment