Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close a Dropdown menu when you click somewhere in the page with jQuery? [duplicate]

I have a simple Dropdown menu that I am showing on inline text links. I am using jQuery click event to show the Dropdown menu when a link is clicked on.

What I would like to do is have the Dropdown menu go back to a hidden state when a click anywhere is made. Right now you have to click the link again to close the menu.

Demo http://codepen.io/jasondavis/pen/sFpwK?editors=101

jQuery

// Show Dropdown Menu when link is clicked
$(function(){
  $(".inline-dropdown-menu").click(function(e){
    $(this).find(".inline-dropdown-menu-list:first").toggle();
    e.preventDefault(); // Stop navigation
  });
});

HTML

<span class="inline-dropdown-menu">
    <a href="">My Link that reveals a DropDown Menu when clicked on<span class="caret"></span></a>

    <ul class="inline-dropdown-menu-list">
        <li class="bottomBorder">
            <a href="" tabindex="-1">alphabetically</a>
        </li>
        <li>
            <a href="" tabindex="-1">2. the first report, alphabetically</a>
        </li>
        <li>
            <a href="" tabindex="-1">3. the first report, alphabetically</a>
        </li>
    </ul>
</span>
like image 888
JasonDavis Avatar asked Mar 19 '23 03:03

JasonDavis


1 Answers

http://codepen.io/anon/pen/JmLsB

$(function () {
    $(".inline-dropdown-menu").click(function (e) {
        $(".inline-dropdown-menu-list").hide(); // to hide other drop down
        $(this).find(".inline-dropdown-menu-list:first").toggle();

        e.preventDefault(); // Stop navigation
    });
});

// to hide drop down if you click other than inline-dropdown-menu class

$(document).click(function (e) {
    var container = $(".inline-dropdown-menu");
    if (!container.is(e.target) && container.has(e.target).length === 0) {
        $(".inline-dropdown-menu-list").hide();
    }
});
like image 196
Vitorino fernandes Avatar answered Mar 20 '23 15:03

Vitorino fernandes