The best way is to check if the dropdown is not already open, and then to use .dropdown('toggle')
.
Couple things to be aware of:
- If you want to trigger it by clicking on another element, you must
kill the click event on the other element– otherwise Bootstrap will
treat it as a click outside of the dropdown and immediately close it. $('.dropdown').addClass('open')
is not a good replacement for
$('.dropdown-toggle').dropdown('toggle')
as suggested in other
answers, because it will cause the dropdown to stay permanently open
instead of closing when you click off of the component.
HTML:
<button class="btn btn-secondary trigger_button">Trigger dropdown</button><br><br>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-toggle="dropdown">
Dropdown
</button>
<div class="dropdown-menu">
Stuff...
</div>
</div>
JS:
$('.trigger_button').click(function(e){
// Kill click event:
e.stopPropagation();
// Toggle dropdown if not already visible:
if ($('.dropdown').find('.dropdown-menu').is(":hidden")){
$('.dropdown-toggle').dropdown('toggle');
}
});
Fiddle example