Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Last active March 29, 2022 09:03
Show Gist options
  • Save bartwttewaall/4ce3bf4cd162634129f8c82febeb86e7 to your computer and use it in GitHub Desktop.
Save bartwttewaall/4ce3bf4cd162634129f8c82febeb86e7 to your computer and use it in GitHub Desktop.
Detect a click event within or outside an element
var parentElement = document.querySelector('.card');
document.addEventListener('click', (event) => {
// option 1
const isClickInside = parentElement.contains(event.target);
if (!isClickInside) // click outside
// option 2
const isNested = event.target.closest('.card') == parentElement;
if (!isNested) // click outside
});
export function documentMouseLeave(callback: () => void) {
document.addEventListener('mouseleave', event => {
const { clientX, clientY } = event;
const outOfBounds = clientY <= 0 || clientX <= 0 || clientX >= window.innerWidth || clientY >= window.innerHeight;
if (outOfBounds) callback();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment