How To: jQuery - Detect Click Event Outside of an Element

To detect a click outside of an element, attach the click event handler to the area outside of the element such as the document. In the event handler check the target for the element or an element descendant by using the jQuery closest method.

Step by Step

HTML for the Container Element

<div id="container">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>

Create the Click Event Handler on the Document

$(document).on("click", function (event) {
  // If the target is not the container or a child of the container, then process
  // the click event for outside of the container.
  if ($("#container").length === 0) {
    console.log("You clicked outside of the container element");


Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License