jQuery: Detect Click Outside an Element
HTML
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<h2>Click on the container or container children to see that the click event within the container.</h2>
<h2>Click outside of the container to see the click event outside of the container.</h2>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<h2>Click event</h2>
<div id="results">
</div>
<div style="position: absolute;bottom: 5px;">
Read about this Fiddle at: <a href="http://jsdev.wikidot.com/howto:2" target="_blank">How To: jQuery - Detect Click Event Outside of an Element</a>
</div>
CSS
#container {
border: 1px solid black;
background-color: green;
display: inline-block;
padding: 10px;
}
div.square {
width: 100px;
height: 100px;
margin: 5px;
display: inline-block;
background-color: blue;
}
#container:hover {
cursor: pointer;
}
#results {
min-height: 50px;
border: 1px solid lightgrey;
padding: 5px;
}
JavaScript
$(function () {
var count = 1;
// Create 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 ($(event.target).closest("#container").length === 0) {
$("#results").prepend("<div>" + count++ + ". You clicked outside of the container element</div>");
}
});
// Create click event handler on the container element.
$("#container").on("click", function () {
$("#results").prepend("<div>" + count++ + ". You clicked inside of the container element</div>");
});
});