3

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

2
  • Your Fiddle works fine for me. Firefox 57.0.3. Commented Dec 29, 2017 at 18:49
  • Hm, not for me. Clicking on the text container does not open the menu, even in Firefox. Commented Dec 29, 2017 at 23:57

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this works. Even with .show() or .hide() it is possible. The only drawback: after clicking the text container, it's not possible to use the toggle button anymore. But in my case this is not relevant...
Welcome. You have to call .show or .hide separately. With .toggle you can do both at the same time. The toggle button does work in the fiddle.
It is not exactly what I am looking for but got me close. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.