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


HTML



Edit in JSFiddle

 
Another plausible way is to use the .closest() method, as shown below:

jQuery


HTML



Edit in JSFiddle

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


HTML



Edit in JSFiddle

That’s all about detecting a click outside an HTML element in JavaScript and jQuery.