Search code examples
dropdownbootstrap-5

Bootstrap 5: How to properly toggle dropdown with another button


So I have a dropdown menu and next to it a button. The aim is for the button to open and close the dropdown menu, and clicking on the text in the dropdown box should also open and close the menu.

I've been trying to adapt the working Bootstrap 3 code from this post Toggle bootstrap button dropdown using another button for Bootstrap 5 but can't get it fully working as I would like it to. Any help at all would be greatly appreciated.

My code is below:

<div class="btn-group">
  <a id="test-dropdown-btn" class="btn dropdown-toggle" data-bs-toggle="dropdown">Select Category</a>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item">All Categories</a></li>
      <li><a class="dropdown-item">Categoty One</a></li>
      <li><a class="dropdown-item">Categoty Two</a></li>
      <li><a class="dropdown-item">Categoty Three</a></li>
      <li><a class="dropdown-item">Categoty Four</a></li>
      <li><a class="dropdown-item">Categoty Five</a></li>
    </ul>
</div>

 <a id="test-btn" class="btn btn-primary" data-bs-toggle="dropdown" data-bs-target=".btn-group">&#9660</a>

jsfiddle here: https://jsfiddle.net/Ernesto1/gefvd0s1/17/


Solution

  • In Bootstrap 5 you can no longer toggle the Dropdown from another element using the data attributes. However, it can be done using JavaScript...

    let trigger = document.getElementById('test-dropdown-btn')
    document.getElementById('test-btn').addEventListener("click", (e)=>{
        bootstrap.Dropdown.getOrCreateInstance(trigger).toggle()
    })
    
    

    Demo


    Note: The auto-close option must be set to false for this to work.