Detect clicks outside an HTML element with JavaScript/jQuery
This post will discuss how to detect clicks outside an HTML element in JavaScript and jQuery.
1. Using jQuery
Here, the idea is to listen to the document click event with jQuery’s .click(handler) method. Then when a click is detected, check if the clicked element isn’t the element itself or a descendant of it. Based on the result, we can say that click is made inside or outside the HTML element. Here’s what the code would look like:
jQuery
|
1 2 3 4 5 6 7 8 9 |
$(document).click(function() { var obj = $("#container"); if (!obj.is(event.target) && !obj.has(event.target).length) { alert("Outside click detected!"); } else { alert("Inside click detected!"); } }); |
HTML
|
1 |
<div id="container"></div> |
Another plausible way is to use the .closest() method, as shown below:
jQuery
|
1 2 3 4 5 6 7 8 9 |
$(document).on("click", function(event) { var obj = $("#container"); if (!$(event.target).closest(obj).length) { alert("Outside click detected!"); } else { alert("Inside click detected!"); } }); |
HTML
|
1 |
<div id="container"></div> |
2. Using JavaScript
In pure JavaScript, you can bind an element handler to listen to click events on the page, and if the target of the click isn’t one of the descendants of the element, we can say that the click is made outside the element.
JS
|
1 2 3 4 5 6 7 8 9 |
document.addEventListener("mouseup", function(event) { var obj = document.getElementById("container"); if (!obj.contains(event.target)) { alert("Outside click detected!"); } else { alert("Inside click detected!"); } }); |
HTML
|
1 |
<div id="container"></div> |
That’s all about detecting a click outside an HTML element in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)