How to open Bootstrap dropdown programmatically

JavascriptTwitter BootstrapTwitter Bootstrap-3

Javascript Problem Overview


I'm trying to open a Bootstrap dropdown when I click a item of another dropdown.

The idea is to select a city from the first drop down - then the script will auto open the second dropdown with areas (and show only areas corresponding to the chosen city).

Here is my JS:

$('#sidebar_filter_city li').click(function(){   
    $('#sidebar_filter_areas').dropdown('toggle');
});

and this is the HTML:

<div class="dropdown form-control">
   <div data-toggle="dropdown" id="sidebar_filter_cities" class="sidebar_filter_menu" data-value="jersey-city">Jersey City<span class="caret caret_sidebar"></span></div>           
   <input type="hidden" name="advanced_city" value="jersey-city">
   <ul id="sidebar_filter_city" class="dropdown-menu filter_menu" role="menu" aria-labelledby="sidebar_filter_cities">
      <li role="presentation" data-value="">All Cities</li>
      <li role="presentation" data-value="jersey-city">Jersey City</li>
      <li role="presentation" data-value="london">London</li>
      <li role="presentation" data-value="new-york">New York</li>
   </ul>        
   </div>
</div>

<div class="dropdown form-control">
    <div data-toggle="dropdown" id="sidebar_filter_areas" class="sidebar_filter_menu">All Areas<span class="caret caret_sidebar"></span> </div>           
        <input type="hidden" name="advanced_area" value="">
           <ul id="sidebar_filter_area" class="dropdown-menu filter_menu" role="menu" aria-labelledby="sidebar_filter_areas">
               <li role="presentation" data-value="">All Areas</li>
               <li role="presentation" data-value="east-harlem" data-parentcity="">East Harlem</li>
               <li role="presentation" data-value="greenville" data-parentcity="">Greenville</li>
               <li role="presentation" data-value="manhattan" data-parentcity="">Manhattan</li>
               <li role="presentation" data-value="northern-brooklyn" data-parentcity="">Northern Brooklyn</li>
               
                  .....
           </ul>        
        </div>    
</div>

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

For Bootstrap 3 you can just add the 'open' class to the dropdown tag. Removing it closes the dropdown.

$('.dropdown').addClass('open'); // Opens the dropdown
$('.dropdown').removeClass('open'); // Closes it

This may work in other versions, but I'm not sure.

Solution 3 - Javascript

Bootstrap's dropdown plugin waits for 'click.bs.dropdown' event to show the menu, so in this case:

$('#sidebar_filter_areas').trigger('click.bs.dropdown');

should work. This will not trigger other 'click' events on same element if any.

Solution 4 - Javascript

dropdown('toggle') works great for me when using the button tag.

JS

$("#mybutton").dropdown('toggle')

HTML

<button class="dropdown-toggle ban" role="button" data-toggle="dropdown" data-target="#" id="mybutton">...</button>

Solution 5 - Javascript

You need to stop the click event from bubbling to parent elements

$('#sidebar_filter_city li').click(function(e){   
    $('#sidebar_filter_areas').dropdown('toggle');
    e.stopPropagation();
});

You can also use return false; which will do the same thing, but this will also preventDefault on the click.

Solution 6 - Javascript

If absolutely none of them are doing the trick, then you can do something like the following:

$('.dropdown').addClass('open'); // substitute with your own selector
$('.dropdown-toggle').attr('aria-expanded', true).focus(); // substitute with your own selector

Although the above will work, I do not recommend using it as it's a bit hacky.

Solution 7 - Javascript

Something I like to use that has a bit more user-expected behavior:

if(!$('#myDropdown').hasClass('show')){
  $('#myDropdown').dropdown('toggle');
}

If it is already open, don't do anything. If it is closed, then it should open.

Solution 8 - Javascript

This works for me.

$('.dropdown-toggle').click(function (ev) {
    ev.stopPropagation();

    $(this).parent().toggleClass('open');
});

Markup:

<div class="dropdown pull-right">
    <button class="btn btn-default dropdown-toggle task-actions" type="button"
            data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
        <img src="{{ asset('img/site/icons/menu.svg') }}" alt="Menu">
    </button>
    <ul id="dropdown-overview" class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
    </ul>
</div>

Solution 9 - Javascript

just use .click() on data-toggle element but do not forget e.stopPropagation()

these one simple line took me for hours, hope it's help :)

Solution 10 - Javascript

If you inspect opened drop down menu you can see selector which changes display of Dropdown menu. In bootstrap v3.0.0 css selector is:

.open > .dropdown-menu {
    display: block;
}

So open class should be added to parent node of element with .dropdown-menu class. In other versions if it has been changed probably correct selector can be found in the same way.

Solution 11 - Javascript

Try this:

$('#sidebar_filter_areas').click();

Solution 12 - Javascript

According to bootstrap docs you can simply use this :

$('.dropdown-toggle').dropdown();

Solution 13 - Javascript

For Bootstrap 4 using Anuglar 6 i used this:

<div class="dropdown-menu" id='logoutDropDownMenu' x-placement="bottom-start" style="position: absolute; transform: translate3d(0px, 40px, 0px); top: 0px; left: 0px; will-change: transform;">

My component ts file has this function

 import { DOCUMENT } from '@angular/common';
 import { Inject } from '@angular/core';

export class HomeComponent implements OnInit {

  private toggleLogout: boolean;

  constructor(@Inject(DOCUMENT) private document: any){}


 toggleButton() {
    if (this.toggleLogout) {
      this.document.getElementById('logoutDropDownMenu').classList.add('show');
    } else {
      this.document.getElementById('logoutDropDownMenu').classList.remove('show');
    }
    this.toggleLogout = !this.toggleLogout;

  }

Solution 14 - Javascript

in Bootstrap 4.x, following components need to be effected:

  • li > .nav-item .dropdown
    • a > .nav-link > aria-expanded
  • div > .dropdown-menu

Adding a click event listener, which triggers toggling a class and a bool value, for those classes make dropdown work with pure javascript as follows:

let status = false
const nav = document.getElementsByClassName('nav-item dropdown')[0]
nav.addEventListener('click', toggleDropdown)
function toggleDropdown () {
   if (status) {
      nav.classList.add('show')
      document.getElementsByClassName('nav-link dropdown-toggle')[0].setAttribute('aria-expanded', ' + status + ')
      document.getElementsByClassName('dropdown-menu').classList.add('show')
   } else {
      nav.classList.remove('show')
      document.getElementsByClassName('nav-link dropdown-toggle')[0].setAttribute('aria-expanded', ' + status + ')
      document.getElementsByClassName('dropdown-menu').classList.remove('show')
   }
   return status = !status
}

Solution 15 - Javascript

You can achieve the same thing using Native JavaScript like this:

 document.getElementById('XYZ').click('open');
It works on all browsers.

Solution 16 - Javascript

most of the time act as a manual action works :

$('#sidebar_filter_city li').click(function(){   
    $('#sidebar_filter_areas').click();
});

Solution 17 - Javascript

Add data-toggle="dropdown" id="dropbox" in HTML like this:

<div data-toggle="dropdown" id="dropbox" 

And in JS/TS:

$('#dropbox').trigger('click.bs.dropdown');

Solution 18 - Javascript

If you use a JS framework like AngularJS, you just need to implement your condition in JS (conditionMenuIsOpen()) and bind display styling of dropdown-menu with this condition in HTML. When condition is true, then display styling will change from hidden to block and the dropdown menu will appear.

<ul class="dropdown-menu" ng-style="vm.conditionMenuIsOpen() && {'display':'block'}">
  ...
</ul>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCreremView Question on Stackoverflow
Solution 1 - JavascriptYarinView Answer on Stackoverflow
Solution 2 - JavascriptmkandeferView Answer on Stackoverflow
Solution 3 - JavascriptEugeneView Answer on Stackoverflow
Solution 4 - JavascriptmendydoView Answer on Stackoverflow
Solution 5 - JavascriptAdam LynchView Answer on Stackoverflow
Solution 6 - JavascriptadamjView Answer on Stackoverflow
Solution 7 - JavascriptReedView Answer on Stackoverflow
Solution 8 - JavascriptLTroyaView Answer on Stackoverflow
Solution 9 - JavascriptPeace SaravudechaView Answer on Stackoverflow
Solution 10 - JavascriptHamed MahdizadehView Answer on Stackoverflow
Solution 11 - JavascriptWellington GasparinView Answer on Stackoverflow
Solution 12 - JavascriptMajiDView Answer on Stackoverflow
Solution 13 - JavascriptLevijatanuView Answer on Stackoverflow
Solution 14 - JavascriptcagcakView Answer on Stackoverflow
Solution 15 - JavascriptVivek MehtaView Answer on Stackoverflow
Solution 16 - JavascriptnopenopeView Answer on Stackoverflow
Solution 17 - JavascriptShashwat GuptaView Answer on Stackoverflow
Solution 18 - JavascriptStefanos KargasView Answer on Stackoverflow