Detect Click Outside Element Using jQuery

Ever wanted to detect click outside an element using jQuery? In this article, I am going to share an easy way to do it and you can apply the same procedure for detecting click outside elements such as div, form, unordered list, etc. Also try the demo to see how it works in real time.

How To Detect Click Outside An Element Using jQuery

Let’s assume that we have a div with ID “my_div”. Now we would like to show an alert when we click inside this div and another alert when we click outside this div. Here’s an example of how it can be done:

<style type="text/css">
#my_div {
	background-color: #FC9;
	padding: 25px;
	border: 1px solid #F60;

<div id="my_div" class="my_class">This is some content. Click inside this div once and click outside this div to see the alerts.</div>

<script type="text/javascript">
$(document).ready(function() {

		var id = $(this).attr('id');		
		alert('You clicked INSIDE the Div with ID #'+ id);		

	$('html').click(function() {		
		alert('You clicked OUTSIDE the div');		

First, we target the div and we attach a click event to it so that we can see an alert when it is clicked upon. To show an alert when we click outside the div, we target the html tag.

Your Turn!

Do you know of any other ways of detecting click outside an element using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!