Hello, I am trying to work on a project which requires me not allow a user to click outside of a particular element, let's say a "<div>" or "<p>", then how can I detect click outside an element using Javascript?
there are some ways to do it, let's take a look at them, one by one:
you can use event.ComposePath()
to check if you have clicked inside the element or not.
const target = document.querySelector('#yourTargetElementId');
document.addEventListener('click', (event) => {
const withinBoundaries = event.composedPath().includes(target)
if (withinBoundaries) {
target.innerText = 'Clicked INSIDE element'
} else {
target.innerText = 'Clicked OUTSIDE element'
}
})
Here is the fiddle to test it: https://jsfiddle.net/orps31tg/
Try this Code to check if element is clicked outside div
var specifiedElement = document.getElementById('yourTargetElementId');
document.addEventListener('click', function(event) {
var isClickInside = specifiedElement.contains(event.target);
if (isClickInside) {
specifiedElement.innerText = 'Clicked INSIDE element'
}
else {
specifiedElement.innerText = 'Clicked OUTSIDE element'
}
});
Check fiddle here: https://jsfiddle.net/orps31tg/3/
You can attach a Event for complete window and another event to check click inside div
$(window).click(function() {
console.log("click outside");
});
$('#yourTargetElementId').click(function(event){
event.stopPropagation();
console.log("click inside");
});
Here is the fiddle to this code: https://jsfiddle.net/mr9ufdL2/
That's it, these were simpler ways to detect click.
Here is the simply javascript method to detect click outside an element or div
document.getElementById('main-container').onclick = function(e) {
if(e.target != document.getElementById('inner-area')) {
document.getElementById('inner-area').innerHTML = 'You clicked outside div';
} else {
document.getElementById('inner-area').innerHTML = 'You clicked inside';
}
}
Here is working fiddle: https://jsfiddle.net/r6jz7o4m/
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly