How to Detect a Click Outside of an Element with jQuery
Topic: JavaScript / jQueryPrev|Next
Answer: Use the event.target
Property
You can use the event.target
property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.
To illustrate how it works we've created a dropdown menu in the following example that will hide and show you a hint message when you click outside of the menu area using jQuery.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Detect Click Outside an Element</title>
<style>
body{
font: 15px Arial, sans-serif;
}
ul{
padding: 0;
list-style: none;
background: #f2f2f2;
border: 1px solid #dedede;
}
ul li{
display: inline-block;
position: relative;
line-height: 21px;
}
ul li a{
display: block;
padding: 8px 25px;
color: #333;
text-decoration: none;
}
ul li a:hover{
color: #fff;
background: #939393;
}
ul.dropdown-menu{
min-width: 100%; /* Set width of the dropdown */
background: #f2f2f2;
display: none;
position: absolute;
z-index: 999;
left: 0;
}
ul.dropdown-menu li{
display: block;
white-space: nowrap;
}
p.hint{
height: 25px;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
// Toggle dropdown menu on click of trigger element
$(".dropdown-toggle").click(function(){
// Hide other dropdown menus in case of multiple dropdowns
$(".dropdown-menu").not($(this).next()).slideUp("fast");
// Toggle the current dropdown menu
$(this).next(".dropdown-menu").slideToggle("fast");
// Showing the hint message
$(".hint").html("A click <b>inside</b> the dropdown is detected.");
});
// Hide dropdown menu on click outside
$(document).on("click", function(event){
if(!$(event.target).closest(".dropdown").length){
$(".dropdown-menu").slideUp("fast");
// Showing the hint message
$(".hint").html("A click <b>outside</b> the dropdown is detected.");
}
});
});
</script>
</head>
<body>
<p class="hint"><!-- Hint text will be inserted here --></p>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle">Services ▾</a>
<ul class="dropdown-menu">
<li><a href="#">Web Design</a></li>
<li><a href="#">Web Development</a></li>
<li><a href="#">Graphic Design</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</body>
</html>
You should avoid using the stopPropagation()
method in such situations as it breaks normal event flow in the DOM tree. It is also considered as a bad practice.
See the tutorial on JavaScript event propagation to learn how event propagate in the DOM tree.
Related FAQ
Here are some more FAQ related to this topic: