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
1
: 188 At:- 6/22/2022 3:54:04 PM
Javascript detect click outside element







1 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.

1
At:- 6/22/2022 4:13:32 PM
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






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