Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a bootstrap dropdown menu with jquery?

Alright, I asked a question yesterday that turned out to be completely off base. I think I'm on more solid ground now but still having an issue. I have a bootstrap dropdown menu in a button group as follows:

<div class="btn-group" id="openItems">
    <button class="btn btn-custom-top dropdown-toggle" data-toggle="dropdown"><span class="caption"></span><span class="caret"></span></button>
    <ul class="dropdown-menu" id="openItemDropdown">
    </ul>
</div>

After moving the mouse out of the menu, I'd like it to close. I almost have it working but not quite.

$(document).ready(function ()
{
    $('.dropdown-menu').mouseleave(function ()
    {

        $(".dropdown-toggle").dropdown('toggle');
    });
});

The problem with this is that it toggles all of the dropdowns on the page. I've tried checking .hasClass('active') on $(this) but it always returns false. I suspect this is because $(this) is actually the .dropdown-menu node rather than the .dropdown-toggle node. However, traversing the nodes is tricky and doesn't seem to work across all browsers. There has GOT to be a way to just always close the lists rather than toggling them.

like image 744
mrplainswalker Avatar asked Oct 08 '13 16:10

mrplainswalker


2 Answers

just add a custom fake class along with dropdown-toggle. for example:

<div class="btn-group" id="openItems">
  <button class="btn btn-custom-top myFakeClass dropdown-toggle" data-toggle="dropdown">
    <span class="caption"></span>
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" id="openItemDropdown"></ul>
</div>

then use that as a selector in the script :

$(document).ready(function () {
  $('.dropdown-menu').mouseleave(function () {
    $(".myFakeClass").dropdown('toggle');
  });
});
like image 73
Bobby5193 Avatar answered Oct 14 '22 02:10

Bobby5193


There's an even easier way to close a Bootstrap dropdown with jQuery:

$j(".dropdown.open").toggle();

This will close all open dropdowns.

Alternately,

$j(".dropdown.open").removeClass("open");

This, without any custom code. Of course, it does require you to use the .dropdown class, even when it is superfluous, as in the case of a btn-group.

like image 3
jpaugh Avatar answered Oct 14 '22 01:10

jpaugh