How to detect click outside an element (or div)?


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?


Asked by:- Vinnu
2
: 2500 At:- 6/22/2022 3:54:04 PM
Javascript detect click outside element







2 Answers
profileImage Answered by:- vikas_jk

there are some ways to do it, let's take a look at them, one by one:

With Pure Javascript

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/

Another Javascript based solution

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/

Using jQuery

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.

2
At:- 6/22/2022 4:13:32 PM Updated at:- 12/24/2022 5:52:27 AM
Thanks for excellent solutions with fiddle, as it helps me in testing output. I will go with 2nd Javascript based solution as it looks good and easy. 0
By : Vinnu - at :- 6/22/2022 4:15:50 PM


profileImage Answered by:- jon

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

0
At:- 12/24/2022 12:23:37 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use