mixable
mixable

Reputation: 1158

Bootstrap 4: open dropdown menu using javascript

I have a simple dropdown menu which looks like this:

<div id="actions" class="dropdown btn-group btn btn-outline-secondary" role="group">
  <div id="actionToggle" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    toggle
  </div>
  <div class="dropdown-menu" role="menu" aria-labelledby="actionToggle">
    <div class="dropdown-header">Actions ...</div>
    <a href="#" class="dropdown-item" name="action1">Action 1</a>
    <a href="#" class="dropdown-item" name="action2">Action 2</a>
    <a href="#" class="dropdown-item" name="action3">Action 3</a>
  </div>
</div>

As described in the docs, it's possible to use JavaScript to open the Dropdown Menu. E.g. using the dropdown("toggle") method in Jquerys onDomready will open the menu when the page is loaded. The following code opens the menu as expected:

$("#actionToggle").dropdown("toggle");

But when I try to use the code inside a Jquery onclick-event handler, it does not open the menu. It's the same code and the event is fired correctly. Any ideas what is going wrong here?

$("#open").on("click", function() {
  $("#actionToggle").dropdown("toggle");
});

The html element I want to click on looks like this:

<div id="open">text</div>

Clicking the text should open the menu, but it does not...

I prepared a JSFiddle to play with the code: https://jsfiddle.net/3ot08j68/1/

The following libraries are used: JQuery 3.2.1, Bootstrap 4.0beta.3, Popper 1.12.9

Upvotes: 3

Views: 10711

Answers (1)

DragonBorn
DragonBorn

Reputation: 1809

Change your code

$("#open").on("click", function() {
  $("#actionToggle").dropdown("toggle");
});

to

$("#open").on("click", function() {
  $(".dropdown-menu").toggle();
});

and it will work. I have updated your fiddle.

Upvotes: 8

Related Questions