Bird
Raised Fist0
Bootsrapmarkup~5 mins

Dropdown events and methods in Bootsrap

Choose your learning style10 modes available
Introduction

Dropdown events and methods help you control and respond to user actions on dropdown menus. They make your website interactive and user-friendly.

When you want to run code right after a dropdown opens or closes.
When you need to open or close a dropdown menu using JavaScript.
When you want to change the dropdown behavior based on user clicks.
When you want to add animations or effects when dropdowns show or hide.
When you want to track user interactions with dropdown menus for analytics.
Syntax
Bootsrap
var dropdownElement = document.querySelector('#myDropdown');

// To show dropdown
var dropdown = new bootstrap.Dropdown(dropdownElement);
dropdown.show();

// To hide dropdown
dropdown.hide();

// Listening to events
dropdownElement.addEventListener('show.bs.dropdown', function () {
  // Code to run before dropdown shows
});
dropdownElement.addEventListener('shown.bs.dropdown', function () {
  // Code to run after dropdown is shown
});
dropdownElement.addEventListener('hide.bs.dropdown', function () {
  // Code to run before dropdown hides
});
dropdownElement.addEventListener('hidden.bs.dropdown', function () {
  // Code to run after dropdown is hidden
});
Note: Replace #myDropdown with your dropdown's ID or selector.
Tip: Events ending with .bs.dropdown are Bootstrap's custom events.
Examples
This example shows an alert when the dropdown finishes opening.
Bootsrap
<button id="myDropdown" class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
  Dropdown button
</button>
<ul class="dropdown-menu" aria-labelledby="myDropdown">
  <li><a class="dropdown-item" href="#">Action</a></li>
  <li><a class="dropdown-item" href="#">Another action</a></li>
</ul>

<script>
  var dropdownElement = document.querySelector('#myDropdown');
  var dropdown = new bootstrap.Dropdown(dropdownElement);

  dropdownElement.addEventListener('shown.bs.dropdown', function () {
    alert('Dropdown is now visible!');
  });
</script>
This example opens the dropdown automatically and closes it after 3 seconds.
Bootsrap
<script>
  var dropdownElement = document.querySelector('#myDropdown');
  var dropdown = new bootstrap.Dropdown(dropdownElement);

  // Open dropdown programmatically
  dropdown.show();

  // Close dropdown after 3 seconds
  setTimeout(() => {
    dropdown.hide();
  }, 3000);
</script>
Sample Program

This page shows a Bootstrap dropdown button. When you click it, the text below changes to tell you if the dropdown is opening, open, closing, or closed. This uses Bootstrap's dropdown events to update the message.

Bootsrap
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Bootstrap Dropdown Events Example</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
  <main class="p-4">
    <button id="myDropdown" class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
      Click me
    </button>
    <ul class="dropdown-menu" aria-labelledby="myDropdown">
      <li><a class="dropdown-item" href="#">First item</a></li>
      <li><a class="dropdown-item" href="#">Second item</a></li>
    </ul>

    <p id="status" class="mt-3" aria-live="polite">Dropdown is closed.</p>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    const dropdownElement = document.querySelector('#myDropdown');
    const status = document.querySelector('#status');
    const dropdown = new bootstrap.Dropdown(dropdownElement);

    dropdownElement.addEventListener('show.bs.dropdown', () => {
      status.textContent = 'Dropdown is opening...';
    });

    dropdownElement.addEventListener('shown.bs.dropdown', () => {
      status.textContent = 'Dropdown is open.';
    });

    dropdownElement.addEventListener('hide.bs.dropdown', () => {
      status.textContent = 'Dropdown is closing...';
    });

    dropdownElement.addEventListener('hidden.bs.dropdown', () => {
      status.textContent = 'Dropdown is closed.';
    });
  </script>
</body>
</html>
OutputSuccess
Important Notes

Use aria-expanded and aria-labelledby for better accessibility.

Bootstrap's JavaScript bundle includes Popper.js, which is needed for dropdown positioning.

Listen to events to add custom behavior without changing Bootstrap's core code.

Summary

Dropdown events let you run code when dropdowns open or close.

Methods like show() and hide() let you control dropdowns with JavaScript.

Use these features to make your site interactive and accessible.

Practice

(1/5)
1. Which Bootstrap dropdown event is triggered just before the dropdown menu is shown?
easy
A. hidden.bs.dropdown
B. shown.bs.dropdown
C. hide.bs.dropdown
D. show.bs.dropdown

Solution

  1. Step 1: Understand dropdown event timing

    The show.bs.dropdown event fires just before the dropdown menu appears.
  2. Step 2: Differentiate from other events

    shown.bs.dropdown fires after showing; hide.bs.dropdown and hidden.bs.dropdown relate to closing.
  3. Final Answer:

    show.bs.dropdown -> Option D
  4. Quick Check:

    Event before showing = show.bs.dropdown [OK]
Hint: Events ending with .bs.dropdown show dropdown states [OK]
Common Mistakes:
  • Confusing 'show' and 'shown' events
  • Mixing show and hide events
  • Assuming event fires after dropdown is visible
2. Which JavaScript method correctly opens a Bootstrap dropdown programmatically?
easy
A. dropdown.toggle()
B. dropdown.open()
C. dropdown.show()
D. dropdown.display()

Solution

  1. Step 1: Recall Bootstrap dropdown methods

    The method toggle() toggles the dropdown menu open or closed programmatically.
  2. Step 2: Eliminate incorrect methods

    open() and display() are not Bootstrap dropdown methods; show() is not a method on the dropdown instance.
  3. Final Answer:

    dropdown.toggle() -> Option A
  4. Quick Check:

    Open dropdown = toggle() method [OK]
Hint: Use toggle() to open or close dropdown programmatically [OK]
Common Mistakes:
  • Using show() which does not exist
  • Assuming open() method exists
  • Confusing toggle() with show()
3. What will be logged to the console when this code runs?
const dropdownElement = document.querySelector('#myDropdown');
const dropdown = bootstrap.Dropdown.getOrCreateInstance(dropdownElement);
dropdownElement.addEventListener('shown.bs.dropdown', () => console.log('Dropdown opened'));
dropdown.show();
medium
A. Dropdown opened
B. No output
C. Error: dropdown.show is not a function
D. Dropdown closed

Solution

  1. Step 1: Understand event listener setup

    The code listens for the shown.bs.dropdown event and logs 'Dropdown opened' when fired.
  2. Step 2: Analyze dropdown.show() effect

    Calling dropdown.show() opens the dropdown and triggers the shown.bs.dropdown event, causing the log.
  3. Final Answer:

    Dropdown opened -> Option A
  4. Quick Check:

    shown.bs.dropdown triggers console log [OK]
Hint: shown.bs.dropdown fires after show() completes [OK]
Common Mistakes:
  • Expecting output before dropdown opens
  • Confusing show() with toggle()
  • Missing event listener setup
4. Identify the error in this code snippet that tries to hide a Bootstrap dropdown:
const dropdownElement = document.querySelector('#menu');
const dropdown = new bootstrap.Dropdown(dropdownElement);
dropdown.close();
medium
A. Using 'new' keyword instead of getOrCreateInstance
B. Selecting element with wrong ID
C. Calling close() method which does not exist
D. Missing event listener for hide event

Solution

  1. Step 1: Check Bootstrap dropdown methods

    Bootstrap dropdown does not have a close() method; it uses toggle() or dispose().
  2. Step 2: Verify object creation

    Using new bootstrap.Dropdown() is valid; the error is not here.
  3. Final Answer:

    Calling close() method which does not exist -> Option C
  4. Quick Check:

    close() method is invalid for Bootstrap dropdown [OK]
Hint: Bootstrap dropdown has no close(), use toggle() or dispose() [OK]
Common Mistakes:
  • Assuming close() method exists
  • Confusing close() with jQuery methods
  • Thinking new keyword causes error
5. You want to run a function only after a Bootstrap dropdown has fully closed. Which event should you listen to, and how do you programmatically close the dropdown?
hard
A. Listen to hide.bs.dropdown event and call dropdown.toggle()
B. Listen to hidden.bs.dropdown event and call dropdown.hide()
C. Listen to hidden.bs.dropdown event and call dropdown.toggle()
D. Listen to hidden.bs.dropdown event and call dropdown.dispose()

Solution

  1. Step 1: Identify event after dropdown closes

    The hidden.bs.dropdown event fires after the dropdown is fully closed.
  2. Step 2: Choose method to close dropdown programmatically

    Use dropdown.hide() to close the dropdown menu.
  3. Final Answer:

    Listen to hidden.bs.dropdown event and call dropdown.hide() -> Option B
  4. Quick Check:

    Close dropdown with hide(), detect close with hidden.bs.dropdown [OK]
Hint: Use hidden.bs.dropdown event and hide() to close dropdown [OK]
Common Mistakes:
  • Listening to hide.bs.dropdown instead of hidden.bs.dropdown
  • Using toggle() which toggles state instead of specifically closing
  • Calling dispose() which removes dropdown instance
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard