Here's a one liner that doesn't require jquery using Node.contains:
// Get arbitrary element with id "my-element"
var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element');
// Listen for click events on body
document.body.addEventListener('click', function (event) {
if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {
console.log('clicked inside');
} else {
console.log('clicked outside');
}
});
If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true
) so this snippet should always work.
Browser support seems to cover pretty much everything according to that MDN page as well.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…