jQuery event.target detect a click outside of an element

Introduction

Use the event.target property to detect a click outside of an element.

This property returns the DOM element that initiated the event.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Detect Click Outside an Element</title>
<style>
    body{//  w w w  .  ja v a 2 s  .  c o  m
        font: 15px;
    }
    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%;
        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-1.12.4.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 inside 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 outside the dropdown is detected.");
        }
    });
});
</script>
</head>
<body>
    <p class="hint"></p>
    <ul>
        <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="#">CSS</a></li>
                <li><a href="#">HTML</a></li>
                <li><a href="#">Java</a></li>
            </ul>
        </li>
        <li><a href="#">Contact</a></li>
    </ul>
</body>
</html>



PreviousNext

Related