Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap Dropdown toggle doesn't work when called from an event handler

I have an element, dropdown, and some jquery to toggle the dropdown dynamically. However, the toggle doesn't work when called from the event handler. I've already tried everything suggested by related Stackoverflow answers, but nothing works :(

JavaScript:

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(){
    $(".dropdown-toggle").dropdown('toggle'); // this doesn't
  });
});

HTML:

<div class="dropdown clearfix">
   <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
   <ul id="dropdown" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
      <li><a tabindex="-1" href="#">Action</a></li>
      <li><a tabindex="-1" href="#">Another action</a></li>
      <li><a tabindex="-1" href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
  </div>
<br>
<div id="click">Click to toggle</div>

And here is the working (not!) sample: http://bootply.com/61988

like image 266
Arman Bimatov Avatar asked May 22 '13 22:05

Arman Bimatov


People also ask

Why is my dropdown menu not working Bootstrap?

Why is my drop down menu not working in bootstrap? Solution : The dropdown should be toggled via data attributes or using javascript. In the above program, we have forgotten to add a data attribute so the dropdown is not working. So add data-bs-toggle="dropdown" to toggle the dropdown.

How do I use dropdown toggle in Bootstrap?

To open the dropdown menu, use a button or a link with a class of . dropdown-toggle and the data-toggle="dropdown" attribute. The . caret class creates a caret arrow icon (), which indicates that the button is a dropdown.

How do I keep my Bootstrap dropdown open?

Set toggle={false} property inside DropdownItem to prevent dropdown from closing.

How do you prevent the dropdown from closing by clicking inside?

Removing the data attribute data-toggle="dropdown" and implementing the open/close of the dropdown can be a solution. Save this answer.


1 Answers

Just stop the event from propagating and it should work.

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(e){
      e.stopPropagation();
    $(".dropdown-toggle").dropdown('toggle');// this doesn't
  });
});

Fiddle

Bootply

like image 154
PSL Avatar answered Sep 29 '22 22:09

PSL