96

This is getting annoying — when I click on an item in a Bootstrap dropdown, the dropdown doesn't close. I have it set up to open a Facebox lightbox when you click the dropdown item but there is a problem with it.

enter image description here


What I have tried

When the item is clicked, I tried doing this:

    $('.dropdown.open').removeClass('open');
    $('.dropdown-menu').hide();

That hides it, but then for some reason it won't open again.

As you can see I really need the dropdown to close, because it looks crappy when it stays open (mainly because the z-index of the dropdown is higher than the Facebox modal box overlay.


Why I'm not using Bootstrap's built-in modal box

If you're wondering why I'm not using the nice-looking modal box built into Bootstrap, it is because:

  1. It doesn't have a way to load content into it with AJAX.
  2. You have to type HTML each time for the modal; with Facebox you can do a simple: $.facebox({ajax:'/assets/ajax/dialogs/dialog?type=block-user&id=1234567'});
  3. It uses CSS3 animations to animate (which looks very nice) but in non-CSS3 browsers it just shows, which doesn't look that nice; Facebox uses JavaScript to fade in so it works in all browsers.
0

24 Answers 24

178

Try this:

$('.dropdown.open .dropdown-toggle').dropdown('toggle');

This may also work for you:

$('[data-toggle="dropdown"]').parent().removeClass('open');
13
  • 3
    I added another method that may work for you. If it doesn't, double check that the div.btn-group element that holds your button has the class "open" assigned to it. Jun 9, 2012 at 21:52
  • 11
    .dropdown('toggle') closes the dropdown but also disables it from opening again! I don't know what is the use of that!
    – orad
    Mar 25, 2013 at 21:57
  • 2
    when I use .dropdown('toggle'), other click handlers attached to items within the dropdown stop working. I don't have this problem when I use the .parent().removeClass('open') method, however.
    – Ben
    Jul 17, 2013 at 20:00
  • 7
    Heads up: removing the open class works, but it doesn't update aria-expanded. Always better to use the API when possible.
    – claviska
    Mar 26, 2015 at 1:55
  • 1
    $('.dropdown.open .dropdown-toggle').dropdown('toggle'); will work on standalone dropdown buttons, to make it also work for dropups and button groups you can do $('.open>.dropdown-toggle').dropdown('toggle');
    – Duvrai
    Jan 11, 2016 at 17:46
27

tryed out most the options from here but none of them realy worked for me. (the $('.dropdown.open').removeClass('open'); did hide it, but if you moused over before clicking anything else it showed up again.

so i endet up doing it whith a $("body").trigger("click")

4
  • That's a good way of doing it too! So when you virtually click on the <body>, it closes the drop down?
    – Nathan
    Jan 22, 2013 at 19:50
  • 4
    yeah the dropdown is listning on click events from the user outside of the menu. :)
    – VeXii
    Jan 22, 2013 at 21:35
  • 1
    @VeXii yes, and that's the reason of it not closing itself on mobile devices. Hope the new bootstrap version 3 ("mobile first") fixes this. Jul 2, 2013 at 10:40
  • 1
    Works without a flaw.
    – Dovy
    Feb 25, 2016 at 19:29
12
$('.open').removeClass('open');

Bootstrap 4 (October 2018):

$('.show').removeClass('show');
1
  • I think this is really the simplest solution, except with Bootstrap 4 you use the class 'show'.
    – Dagmar
    Oct 9, 2018 at 9:33
7

This can be done without writing JavaScript code by adding attribute data-toggle="dropdown" into anchor tag as shown below:

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#" data-toggle="dropdown">Action</a></li>
    <li role="presentation"><a role="menuitem" tabindex="-1" href="#" data-toggle="dropdown">Another action</a></li>
  </ul>
</div>

1
  • 1
    The simpliest and most relevant answer for me. Well explained. Thanks
    – Simmoniz
    Nov 26, 2015 at 19:41
6

You only need to do $('.dropdown.open').removeClass('open'); remove second line which hides the dropdown menu.

1
  • 3
    But this will not change the aria-attribute.
    – dude
    Nov 15, 2015 at 14:15
6

This is what worked for me:

$(this).closest(".dropdown").find(".dropdown-toggle").dropdown("toggle");
5

Try this!

.removeClass("open").trigger("hide.bs.dropdown").trigger("hidden.bs.dropdown");

OR

$(clicked_element).trigger("click");

It always work for me.

1
  • U the king! the best thing for me! Tnx!
    – Dudi
    Sep 26, 2018 at 13:05
4

The selected answer didn't work for me, but I'm thinking it's because of the newer version of Bootstrap. I ended up writing this:

$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');

Hopefully that's helpful to someone else in the future.

1
  • Thanks for the answer. I believe I am still on Bootstrap 2.2.
    – Nathan
    May 20, 2013 at 21:50
3

Why use my method, because if the user gets out of the div, this metod allows the user a certain delay before the submenus dissapear. It's just like using the superfish plugin.

1) First download hover intent javascript

Link here : Hover intent javascript

2)Here is my code to execute

$(document).ready(function(){

        var config = {    
            over: showBootrapSubmenu,   
            timeout: 500,
            out: hideBootrapSubmenu  
        };

        function showBootrapSubmenu(){  
             $(this).addClass('open');
        }
        function hideBootrapSubmenu(){  
          $(this).removeClass('open');
            }

        //Hover intent for Submenus
        $(".dropdown").hoverIntent(config);

    });
2
$('.dropdown.open').removeClass('open');
2

Reading the documentation and using JavaScript it could be done using the toggle method:

$('.button-class').on('click',function(e) {
    e.preventDefault();
    $('.dropdown-class').dropdown('toggle');
}

You can read about it in: http://getbootstrap.com/javascript/#dropdowns-methods

2

It may have been added in retrospect (though, that feature is not documented, even in Bootstrap 4.3.1), but you can simply call it with a hide parameter. Just make sure to call it on the toggler element. Like so:

$('.dropdown-toggle').dropdown('hide');
// or
$('[data-toggle="dropdown"]').dropdown('hide');

Of course, this also works in reverse with show.

1
  • It's referred to obliquely in the next section as "the hide instance method".
    – beasy
    Nov 13, 2021 at 19:05
1

Try to open HTML with Bootstrap Modal, I use this code:

$(function() {
     $('a[data-toggle=modal]').click(function(e) {
          e.preventDefault();
          var page = $(e.target).attr('href');
          var url = page.replace('#','');
          $(page).on('show', function () {
              $.ajax({
              url: "/path_to/"+url+".php/html/...",
              cache: false,
              success: function(obj){
                   $(page).css('z-index', '1999');
                   $(page).html(obj);
              }
              });
         })
     });
}); 

and the link is like this:

<a href="#my_page" data-toggle="modal">PAGE</a>
1

Here is my solution on how to close the button dropdown and toggle the button :

$(".btn-group.open", this)
    .trigger("click")
    .children("a.dropdown-toggle")
    .trigger("blur")

Where "this" is a global container of the button group.

1

Bootstrap 4.1:

$(".dropdown-link").closest(".dropdown-menu").removeClass('show');
1

Selecting by attribute is the slow way. Here is the fastest solution to hide the opened dropdown:

$(".dropdown-menu.show").parent().dropdown("toggle");

or use following, if the .dropdown-menu is not the next children element (find the closest parent dropdown control):

$(".dropdown-menu.show").closest(".dropdown").dropdown("toggle");
0

this worked for me, i had a navbar and several pulldown menus.

$(document).ready(function () {
    $('a.dropdown-toggle').each(function(){
        $(this).on("click", function () {
            $('li.dropdown').each(function () {
                $(this).removeClass('open');
            });
        });
    });
});
0

The easiest way to do this is: you add a hide label:

<label class="hide_dropdown" display='hide'></label>

then everytime you want to hide dropdown, you call:

$(".hide_dropdown").trigger('click');
0

Don't know if this will help anyone (maybe it is too specific to my case, and not to this question) but for me this worked:

$('.input-group.open').removeClass('open');
0

After click:

// Hide mobile menu
$('.in,.open').removeClass('in open');
// Hide dropdown
$('.dropdown-menu').css('display','none');
setTimeout(function(){
    $('.dropdown-menu').css('display','');
},100);
0

Use class="dropdown-toggle" on the anchor tag, then when you click on the anchor tag it will close the bootstrap dropdown.

0

Hey this simple jQuery trick should help.

$(".dropdown li a").click(function(){
$(".dropdown").removeClass("open");
});
0

The easist way:

  $('.navbar-collapse a').click(function(){
    $('.navbar-toggle').trigger('click')
  })
0

you can use this code in your current event handler

$('.in,.open').removeClass('in open');

in my scenario I used when ajax call complete

jQuery(document).on('click', ".woocommerce-mini-cart__buttons .wc-forward.checkout", function() {
    var _this = jQuery(this);
    ajax_call(_this.attr("data-ajax-href"), "checkout-detail");
    $('.in,.open').removeClass('in open');
    return false;
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.