Alvaro Alvaro - 1 year ago 71
Javascript Question

Bootstrap dropdown-menu doesn't get close when clicking an element

I'm firing the bootstrap dropdown menu by using the javascript function

as stated in their docs.

Usually dropdowns would hide whenever you click outside them or you select one of their options.

This doesn't happen when firing it through javascript.

In this reproduction you'll see two menus:

  • One which works as expected as its fired using the "components" trigger

  • And another one, using the right click, which doesn't work as expected. (it doesn't get closed on click outside or even on element click)

I was able to "manually" get rid of the dropdown menu when clicking outside it by using the following:


But I'm not quite sure why dropdown menus don't work in the same way as when you fire them by the normal procedure.
And having to manually hide them doesn't seem like the best solution...

Answer Source

I got an answer from boostrap issues forum in which they explained how to deal with it:

B. You're missing a <div class="dropdown"> around the <ul class="dropdown-menu">

C. You're missing an element with data-toggle="dropdown" (Not explicitly documented, but followed by all the examples and related to the warning in )

Here's a reproduction of the solution. (right anywhere click to see the dropdown menu)

HTML markup

<div class="wrapper">
    <span data-toggle="dropdown"></span>
    <ul class="dropdown-menu" id="menu">
        <li><a href="#">Download file</a></li>
        <li><a href="#">Upload file</a></li>


//context menu for orders table
$(document).on("contextmenu", "body", function (event) {
    //we won't show the default context menu

    //showing it close to our cursor
        top: (event.pageY) + "px",
        left: (event.pageX) + "px"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download