Twitter Bootstrap: Call a js function when a dropdown is closed

In the end, the only reliable method that I found was to use jquery's data api to store the state of the dropdown and add click events to the button and the document.

$(document).ready(function() {

    $('#dropdown').data('open', false);

    $('#dropdown-button').click(function() {
        if($('#dropdown').data('open')) {
            $('#dropdown').data('open', false);
            update_something();
        } else
            $('#dropdown').data('open', true);
    });

    $(document).click(function() {
        if($('#dropdown').data('open')) {
            $('#dropdown').data('open', false);
            update_something();
        }
    });

});

This is how Bootstrap v2.3.2 closes the menu no matter what you click on:

$('html').on('click.dropdown.data-api', function () {
    $el.parent().removeClass('open')
});

If you're using v2.x, this could be used to know when a menu will be closed. However, keep in mind that this is triggered on every click. If you only need to execute something when a menu is really closed (which is probably all the time), you'll need to track when one is opened in the first place. The accepted answer is probably a better solution in that regard.

In Boostrap v3.0.0, however, the drop menu supports four separate events:

show.bs.dropdown: This event fires immediately when the show instance method is called.

shown.bs.dropdown This event is fired when the dropdown has been made visible to the user (will wait for CSS transitions, to complete).

hide.bs.dropdown This event is fired immediately when the hide instance method has been called.

hidden.bs.dropdown This event is fired when the dropdown has finished being hidden from the user (will wait for CSS transitions, to complete).

From Bootstrap's documentation.


From twitter bootstrap official page:

$('#myDropdown').on('hide.bs.dropdown', function () {
  // do something…
});

hide.bs.dropdown is one of 4 events described here.

Update (13-Apr-16)

These events also work same in Bootstrap 4. Bootstrap v4 Documentation.