How to Detect a Click Outside of an Element with jQuery


Use the Property

You can use the 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">
<meta charset="utf-8">
<title>jQuery Detect Click Outside an Element</title>
        font: 15px Arial, sans-serif;
        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;
        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;
        height: 25px;
<script src=""></script>
    // Toggle dropdown menu on click of trigger element
        // Hide other dropdown menus in case of multiple dropdowns
        // Toggle the current dropdown menu
        // 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){
            // Showing the hint message
            $(".hint").html("A click <b>outside</b> the dropdown is detected.");
    <p class="hint"><!-- Hint text will be inserted here --></p>
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle">Services &#9662;</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>
        <li><a href="#">Contact</a></li>