How to hide dropdown menu on click outside of the element in jQuery

  38262 views   2 years ago jQuery

Use the jQuery on() method

You can use the jQuery click() method in combination with the on() method to hide the dropdown menu when the user click outside of the trigger element.

Let's take a look at the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>jQuery Hide Dropdown on Click Outside</title>
        padding: 0;
        list-style: none;
        background: #f2f2f2;
    ul li{
        display: inline-block;
        position: relative;
        line-height: 21px;
        text-align: left;
    ul li a{
        display: block;
        padding: 8px 25px;
        color: #333;
        text-decoration: none;
    ul li a:hover{
        color: #fff;
        background: #939393;
    ul li ul.dropdown-menu{
        min-width: 100%; /* Set width of the dropdown */
        background: #f2f2f2;
        display: none;
        position: absolute;
        z-index: 999;
        left: 0;
    ul li ul.dropdown-menu li{
        display: block;
<script src=""></script>
        // Show hide popover
    $(document).on("click", function(event){
        var $trigger = $(".dropdown");
        if($trigger !== && !$trigger.has({
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li class="dropdown">
            <a href="#">Products &#9662;</a>
            <ul class="dropdown-menu">
                <li><a href="#">Laptops</a></li>
                <li><a href="#">Monitors</a></li>
                <li><a href="#">Printers</a></li>
        <li><a href="#">Contact</a></li>


Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]