Last active
March 29, 2022 09:03
-
-
Save bartwttewaall/4ce3bf4cd162634129f8c82febeb86e7 to your computer and use it in GitHub Desktop.
Detect a click event within or outside an element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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