Detect Click Inside Outside Element JavaScript Example

Hello devs,

In this tutorial, I am going to share with you that how to detect click outside element javascript. So from this tutorial, you will learn to detect click outside element jquery. I will show you the source code of 

detect click inside/outside of element with single event handler. 

Sometimes in our application on client-side, we need to detect click inside/outside of element with single event handler in javascript. So let's see the example code of detect click outside element javascript.

Example code with vanilla javascript:

// 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');
    }
});

 

Using jQuery

$(function() {
  $("body").click(function(e) {
    if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {
      alert("Inside div");
    } else {
      alert("Outside div");
    }
  });
})

 

Read also: How to Disable Click Event Outside a Div in JavaScript

 

Hope it can help you.

 

#javascript #jquery