Bootstrap Dropdowns

You will discover how to include drop-down menus into different Bootstrap elements in this article.


Creating Dropdown Menus with Bootstrap

The dropdown menu is commonly used within the navigation header to display a list of related links when a user hovers the mouse or clicks on the trigger element.

With the Bootstrap dropdown plugin, you can easily add toggleable dropdown menus to various elements, such as links, buttons, button groups, navbar, tabs, pills nav, and more, without the need for JavaScript code.

Adding Dropdowns via Data Attributes

Bootstrap provides a simple and elegant method to add dropdown menus to elements using data attributes. The example below illustrates the minimal markup required to add a dropdown menu to a hyperlink using data attributes.

<div class="m-4">
    <div class="dropdown">
        <a href="#" class="dropdown-toggle" data-bs-toggle="dropdown">Dropdown</a>
        <div class="dropdown-menu">
            <a href="#" class="dropdown-item">Images</a>
            <a href="#" class="dropdown-item">Edit</a>
        </div>
    </div>
</div>

This basic example showcases the fundamental form of Bootstrap dropdowns. Let's examine each part of the Bootstrap dropdown component in detail.

Explanation of Code

The Bootstrap dropdown consists of two main components: the dropdown trigger element, which can be a hyperlink or button, and the dropdown menu itself.

  • The .dropdown class is used to define a dropdown menu.
  • The .dropdown-toggle class identifies the trigger element, which is a hyperlink in this case. The data-bs-toggle=dropdown attribute on the trigger element is essential for toggling the dropdown menu.
  • The <div> element with the class .dropdown-menu constructs the dropdown menu, typically containing related links or actions.

Likewise, you can apply dropdowns to buttons and nav components. The following section presents various common implementations of the Bootstrap dropdown.


Dropdowns within a Navbar

You may learn how to add dropdowns to a navbar by looking at the instances below.

<ul class="nav navbar-nav">
<li class="nav-item">
    <a href="#" class="nav-link">Home</a>
</li>
<li class="nav-item dropdown">
    <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">Messages</a>
    <div class="dropdown-menu">
        <a href="#" class="dropdown-item">Inbox</a>
        <a href="#" class="dropdown-item">Sent Items</a>
        <div class="dropdown-divider"></div>
        <a href="#"class="dropdown-item">Trash</a>
    </div>
</li>
</ul>

Note: You can separate the links inside a dropdown menu by using the class .dropdown-divider on an empty <div> element.


Dropdowns within Navs

In this example, you will learn how to incorporate dropdown menus into pills navs.

<ul class="nav nav-pills mb-5">
        <li class="nav-item">
            <a href="#" class="nav-link active">Home</a>
        </li>
        <li class="nav-item dropdown">
            <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">Messages</a>
            <div class="dropdown-menu">
                <a href="#" class="dropdown-item">Inbox</a>
                <a href="#" class="dropdown-item">Sent Items</a>
            </div>
        </li>
    </ul>

To convert a dropdown menu into a tab dropdown, simply replace the class .nav-pills with .nav-tabs without any other changes in the markup.

Dropdowns within Buttons

You may learn how to add dropdowns to a major buttons using the instances that follows.

<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Primary</button>
<div class="dropdown-menu">
    <a href="#" class="dropdown-item">Menu</a>
    <a href="#" class="dropdown-item">Images</a>
    <div class="dropdown-divider"></div>
    <a href="#" class="dropdown-item">Edit</a>
</div>
</div>

Bootstrap Split Button Dropdowns

You may learn how to include dropdowns in split buttons by looking at the instances below.

<div class="btn-group">
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
    <span class="visually-hidden">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
    <a href="#" class="dropdown-item">Menu</a>
    <a href="#" class="dropdown-item">Images</a>
    <div class="dropdown-divider"></div>
    <a href="#" class="dropdown-item">Edit</a>
</div>
</div>

Tip: To resize the buttons in the dropdowns, you can utilize Bootstrap's button relative sizing classes like .btn-lg and .btn-sm on the .btn element.


Dropdowns Inside Button Groups

To create dropdown menus inside a button group, place a .btn-group along with the dropdown markup within another .btn-group, as demonstrated in the example.

<div class="btn-group">
<button type="button" class="btn btn-primary">Button</button>
<button type="button" class="btn btn-primary">Another Button</button>
<div class="btn-group">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>
    <div class="dropdown-menu">
        <a href="#" class="dropdown-item">Images</a>
        <a href="#" class="dropdown-item">Download</a>
        <div class="dropdown-divider"></div>
        <a href="#" class="dropdown-item">Music</a>
    </div>
</div>
</div>

In a similar manner, dropdowns may be created within button groups that are stacked vertically, as shown here:

<div class="btn-group-vertical">
<button type="button" class="btn btn-primary">Button</button>
<button type="button" class="btn btn-primary">Another Button</button>
<div class="btn-group">
    <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropdown</button>
    <div class="dropdown-menu">
        <a href="#" class="dropdown-item">Menu</a>
        <a href="#" class="dropdown-item">Images</a>
        <div class="dropdown-divider"></div>
        <a href="#" class="dropdown-item">Edit</a>
    </div>
</div>
</div>

Creating Dropup, Dropleft and Dropright Menus

You can position the dropdown menus above, left, or right of the elements by adding additional classes: .dropup, .dropstart, and .dropend, respectively, to the parent element (i.e., the .btn-group element).

<!-- Dropup menu -->
    <div class="btn-group dropup">
        <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Dropup</button>
        <div class="dropdown-menu">
            <a href="#" class="dropdown-item">Menu</a>
            <a href="#" class="dropdown-item">Image</a>
            <div class="dropdown-divider"></div>
            <a href="#" class="dropdown-item">Edit</a>
        </div>
    </div>

Creating the Right Aligned Dropdown Menus

For right-aligned dropdown menus, include the class .dropdown-menu-end to the .dropdown-menu base class.

<div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Right-aligned Dropdown Menu</button>
        <div class="dropdown-menu dropdown-menu-end">
            <a href="#" class="dropdown-item">Menu</a>
            <a href="#" class="dropdown-item">Image</a>
            <div class="dropdown-divider"></div>
            <a href="#" class="dropdown-item">Edit</a>
        </div>
    </div>

Adding Headers to Dropdown Items

To label a section of menu items in the dropdown, you can optionally add a menu header using the class .dropdown-header on a <div> element.

<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Products</button>
<div class="dropdown-menu">
    <div class="dropdown-header">ELECTRONICS</div>
    <a href="#" class="dropdown-item">Washing machine</a>
    <a href="#" class="dropdown-item">Air cooler</a>
    <a href="#" class="dropdown-item">Refrigerator</a>
    <div class="dropdown-header">FASHION</div>
    <a href="#" class="dropdown-item">Clothing</a>
    <a href="#" class="dropdown-item">Footers</a>
</div>
</div>

Disable Items within a Dropdown

To visually disable menu items in the dropdown, apply the class .disabled. If you also want to prevent the links from being clickable, you can typically remove the anchor's href attribute using JavaScript or manually.

<div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown">Reports</button>
        <div class="dropdown-menu">
            <a href="#" class="dropdown-item">View</a>
            <a href="#" class="dropdown-item">Download</a>
            <a href="#" class="dropdown-item disabled" tabindex="-1">Edit / Delete</a>
        </div>
    </div>

Adding Dropdowns via JavaScript

Alternatively, you can manually add dropdowns using JavaScript by calling the dropdown() Bootstrap method with the id or class selector of the link or button element.

<script>
                    $(document).ready(function () {
                        $(".dropdown-toggle").dropdown();
                    });  
</script>

Note: Regardless of whether you use JavaScript or data attributes to trigger the dropdown, the data-bs-toggle=dropdown attribute remains necessary for the dropdown's trigger element.


Bootstrap Dropdown Options

You have the option to customize the functionality of a dropdown by passing certain options to the dropdown() Bootstrap method. These options can be specified using data attributes or JavaScript.

To set dropdown options via data attributes, simply append the option name to data-bs-, such as data-bs-display=static, among others. It's important to note that when using data attributes, you should change the case type of the option name from camelCase to kebab-case. For instance, use data-bs-auto-close=false instead of data-bs-autoClose=false.

  1. Boundary: Type: string | element, Default: 'clippingParents'

    Overflow constraint boundary of the dropdown menu (applies only to Popper's preventOverflow modifier). It can also accept an HTMLElement reference (via JavaScript only).

  2. Reference: Type: string | element | object, Default Value: 'toggle'

    Reference element of the dropdown menu. Accepts the values of 'toggle', 'parent', an HTMLElement reference, or an object providing getBoundingClientRect.

  3. Display: Type: string, Default Value: 'dynamic'

    By default, Bootstrap uses Popper for dynamic positioning. You can disable this with 'static'.

  4. Offset: Type: array | string | function, Default: [0, 2],

    Specify the offset of the dropdown relative to its target. You can pass a string in data attributes with comma-separated values like: data-bs-offset="10,20".

  5. AutoClose: Type: boolean | string, Default Value: true

    Configure the auto-close behavior of the dropdown:

    • true - the dropdown will be closed by clicking outside or inside the dropdown menu.
    • false - the dropdown will be closed by clicking the toggle button and manually calling the hide or toggle method. Also, the dropdown will not be closed by pressing the esc key.
    • 'inside' - the dropdown will be closed (only) by clicking inside the dropdown menu.
    • 'outside' - the dropdown will be closed (only) by clicking outside the dropdown menu.

For further details on the choices listed above, consult the Popper.js document.


Bootstrap Dropdown Methods

The default dropdown mechanism for bootstrap is as follows:

toggle: The dropdown menu of a certain navbar or tabbed navigating is toggled using this way.

<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#myDropdown").dropdown("toggle");
    });
    </script>

show: With this technique, a specific navbar or tabbed navigation's dropdown menu is displayed.

<script>
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#myDropdown").dropdown("show");
});
</script>

hide: The dropdown menu of a certain navbar or tabbed navigational is hidden using this technique.

<script> 
$("#hideBtn").click(function () {
    $("#myDropdown").dropdown("hide");
});
</script>

update: The dropdown of an element is updated using this approach.

<script>
$("#updateBtn").click(function () {
    $("#myDropdown").dropdown("update");
});
</script>

Bootstrap Dropdown Events

Furthermore, there are standard Bootstrap events available to enhance the dropdown functionality.

All dropdown events are triggered at the toggling element and then bubbled up. This allows you to add event listeners on the .dropdown-menu's parent element. Additionally, you can use the event.relatedTarget to target the toggling anchor element.

  • show.bs.dropdown: When the display instances method is called, this event occurs instantly.
  • shown.bs.dropdown: As soon as the consumer can see the dropdown menu and CSS transitions are complete, this event is dispatched.
  • hide.bs.dropdown: The instant the hide instances method is invoked, this event is triggered.
  • hidden.bs.dropdown: When the consumer is finished seeing the dropdown hidden and all CSS transitions have finished, this event is fired.

The dropdown link's text content is displayed when visitors clicked on it in the illustration below.

<script>
$(document).ready(function () {
    $(".dropdown").on("show.bs.dropdown", function (e) {
        var linkText = $(e.relatedTarget).text(); // Get the link text
        alert("Click on OK button to view the dropdown menu for - " + linkText);
    });
});
</script>

FAQ

What is a Bootstrap Dropdown?

A Bootstrap Dropdown is a UI component provided by the Bootstrap framework that allows you to create a button or link that, when clicked, displays a menu of options or content. It's a common way to organize and display various choices or actions in a compact and user-friendly manner.

How do you create a basic Bootstrap Dropdown?

To create a basic Bootstrap Dropdown, you need to use the <div> element with the class dropdown. Inside the <div>, you place a button or a link with the class btn and dropdown-toggle, and also include a <div> with the class dropdown-menu containing the dropdown items.

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="simpleDropdown" data-bs-toggle="dropdown" aria-expanded="false">
        Select Option
    </button>
    <ul class="dropdown-menu" aria-labelledby="simpleDropdown">
        <!-- Dropdown items go here -->
    </ul>
</div>

What role does the data-toggle attribute play in a Bootstrap Dropdown?

The data-toggle attribute is used to specify the behavior that triggers the dropdown to open. It is set to 'dropdown' to indicate that clicking on the designated element (usually a button or a link) will open the dropdown menu.

<button class="btn btn-primary dropdown-toggle" type="button" id="toggleAttributeDropdown" data-bs-toggle="dropdown" aria-expanded="false">
    Toggle Attribute Dropdown
</button>

How can you place a Bootstrap Dropdown inside a Navbar?

To place a Bootstrap Dropdown inside a Navbar, you can use the navbar-nav class for the <ul> element inside the Navbar. Then, create a list item with the class nav-item dropdown and place your dropdown components within it.

What is the purpose of the data-target attribute in a Bootstrap Dropdown?

The data-target attribute is used to specify the ID of the dropdown content that should be displayed when the dropdown is triggered. This attribute is used in conjunction with the data-toggle attribute to associate the trigger element with the dropdown content.

How can you create a Split Button Dropdown in Bootstrap?

To create a Split Button Dropdown, you need to include a regular button and a separate button with a down caret icon. The regular button triggers the default action, while the button with the caret triggers the dropdown menu. Use the dropdown-toggle-split class for the dropdown-triggering button.

<div class="btn-group">
    <button class="btn btn-primary" type="button">Main Action</button>
    <button class="btn btn-primary dropdown-toggle dropdown-toggle-split" type="button" id="splitDropdown" data-bs-toggle="dropdown" aria-expanded="false">
        <span class="visually-hidden">Toggle Dropdown</span>
    </button>
    <ul class="dropdown-menu" aria-labelledby="splitDropdown">
        <!-- Dropdown items go here -->
    </ul>
</div>

Can you disable a Bootstrap Dropdown?

Yes, you can disable a Bootstrap Dropdown by adding the disabled class to the trigger button or link. This will prevent the dropdown from opening when the user interacts with the trigger element.

How can you customize the appearance of a Bootstrap Dropdown?

You can customize the appearance of a Bootstrap Dropdown using CSS classes and your own custom styles. Bootstrap provides various classes for styling dropdowns, such as dropdown-primary, dropdown-secondary, and more. You can also override these styles with your own CSS rules.

<button class="btn btn-danger dropdown-toggle" type="button" id="customDropdown" data-bs-toggle="dropdown" aria-expanded="false">
    Custom Dropdown
</button>

What is a Dropdown Header and Divider in Bootstrap?

A Dropdown Header in Bootstrap is a non-selectable heading that can be placed within a dropdown menu to separate and label groups of related items. It is created using the dropdown-header class.

A Dropdown Divider is a horizontal line that separates items within a dropdown menu. To create one, use the dropdown-divider class within the dropdown menu to visually separate items.

<ul class="dropdown-menu" aria-labelledby="headerDividerDropdown">
    <h6 class="dropdown-header">Header</h6>
    <div class="dropdown-divider"></div>
    <li><a class="dropdown-item" href="#">Option 1</a></li>
    <li><a class="dropdown-item" href="#">Option 2</a></li>
    <!-- Add more options as needed -->
</ul>

What is the purpose of the data-display attribute in Bootstrap Dropdowns?

The data-display attribute is used to specify the way the selected dropdown item is displayed in the trigger button or link. It can be set to 'dynamic' to automatically display the selected item, or 'static' to keep the original content.

What is the purpose of the data-offset attribute in a Bootstrap Dropdown?

The data-offset attribute is used to specify the pixel offset from the top of the dropdown's parent element. This can be useful when you want to fine-tune the position of the dropdown in relation to the trigger element.

What are Dropup menus in Bootstrap?

Dropup menus in Bootstrap are essentially dropdown menus that open upwards instead of downwards. They are useful when there's limited space below the trigger element or when it makes more sense to display the menu above.

How can you position a Bootstrap Dropdown to the right instead of the default left?

By default, Bootstrap Dropdowns open towards the left. To make them open towards the right, add the dropdown-menu-right class to the <div> with the dropdown-menu class. This will align the dropdown menu to the right of the trigger element.

Can you add icons to Bootstrap Dropdown items?

Yes, you can add icons to Bootstrap Dropdown items by including the appropriate icon elements (such as <i>, <span>, or <svg>) inside the dropdown item's HTML. Then, apply the necessary icon classes, such as those from FontAwesome or Bootstrap's built-in icon classes.

<ul class="dropdown-menu" aria-labelledby="iconDropdown">
<li><a class="dropdown-item" href="#"><i class="bi bi-house-door"></i> Home</a></li>
<li><a class="dropdown-item" href="#"><i class="bi bi-gear"></i> Settings</a></li>
<!-- Add more options with icons as needed -->
</ul>

What is the purpose of the show and hide events for Bootstrap Dropdowns?

The show event is triggered when a dropdown is about to be displayed, while the hide event is triggered just before the dropdown is hidden. These events allow you to execute custom JavaScript code when the dropdown's visibility changes.

What is the difference between .dropdown and .btn-group in Bootstrap?

Both .dropdown and .btn-group classes are used to create dropdown menus, but they offer different levels of styling and functionality. The .dropdown class is simpler and more lightweight, while the .btn-group class is used to create button groups that can contain dropdowns and other buttons.

How can you center-align the contents of a Bootstrap Dropdown menu?

To center-align the contents of a Bootstrap Dropdown menu, you can use custom CSS to set the text-align property of the .dropdown-menu class to center. This will horizontally center-align the text and other elements within the dropdown menu.

How can you create a responsive Bootstrap Dropdown?

Bootstrap Dropdowns are responsive by default, as they adapt to various screen sizes. However, you can fine-tune the responsiveness by adjusting the placement of the dropdown menu, using utility classes like dropdown-menu-right, and making sure your styles don't break the layout on smaller screens.

Is it possible to customize the animation duration of Bootstrap Dropdowns?

Yes, you can customize the animation duration of Bootstrap Dropdowns by modifying the CSS transitions applied to the .dropdown-menu class. Adjust the transition property to change the animation duration and easing function.

How do you create a right-aligned Bootstrap Dropdown menu?

Right-align a Bootstrap Dropdown menu by adding the dropdown-menu-end class to the <ul> element:

<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="rightAlignDropdown">
    <!-- Dropdown items go here -->
</ul>

How do you create a Bootstrap Dropdown with a badge on an option?

Add a badge to a Bootstrap Dropdown option using the badge class:

<ul class="dropdown-menu" aria-labelledby="badgeDropdown">
    <li><a class="dropdown-item" href="#">Option 1 <span class="badge bg-primary">New</span></a></li>
    <li><a class="dropdown-item" href="#">Option 2</a></li>
</ul>

How do you create a Bootstrap Dropdown with multilevel nested options?

Implement multilevel nested options in a Bootstrap Dropdown by adding sub <ul> elements within the main <ul>:

<ul class="dropdown-menu" aria-labelledby="nestedDropdown">
    <li><a class="dropdown-item" href="#">Option 1</a></li>
    <li>
        <a class="dropdown-item" href="#">Option 2</a>
        <ul class="dropdown-menu">
            <li><a class="dropdown-item" href="#">Suboption 1</a></li>
            <li><a class="dropdown-item" href="#">Suboption 2</a></li>
        </ul>
    </li>
    <!-- Add more options as needed -->
</ul>

How can you dynamically populate a Bootstrap Dropdown using JavaScript?

Dynamically populate a Bootstrap Dropdown using JavaScript by updating the content of the dropdown menu based on user interactions or external data:

<div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" id="dynamicDropdown" data-bs-toggle="dropdown" aria-expanded="false">
        Select Option
    </button>
    <ul class="dropdown-menu" aria-labelledby="dynamicDropdown" id="dynamicDropdownContent">
        <!-- Dropdown items will be dynamically added here -->
    </ul>
</div>

<script>
    const options = ['Dynamic Option 1', 'Dynamic Option 2'];
    const dropdownContent = document.getElementById('dynamicDropdownContent');

    options.forEach(option => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `<a class="dropdown-item" href="#">${option}</a>`;
        dropdownContent.appendChild(listItem);
    });
</script>

How do you handle a Bootstrap Dropdown selection using jQuery?

Use jQuery to handle Bootstrap Dropdown selection events, providing additional functionality when an option is chosen:

<script>
    $(document).ready(function () {
        $('.dropdown-menu a').on('click', function () {
            // Handle the selected option
            alert('Selected: ' + $(this).text());
        });
    });
</script>

How can you create a Bootstrap Dropdown with a dark theme?

Apply a dark theme to a Bootstrap Dropdown by using Bootstrap's contextual classes like bg-dark and text-light:

<div class="dropdown">
    <button class="btn btn-dark dropdown-toggle" type="button" id="darkThemeDropdown" data-bs-toggle="dropdown" aria-expanded="false">
        Dark Dropdown
    </button>
    <ul class="dropdown-menu bg-dark text-light" aria-labelledby="darkThemeDropdown">
        <!-- Dropdown items go here -->
    </ul>
</div>

How do you create a Bootstrap Dropdown with a maximum height and scrolling options?

Set a maximum height and enable scrolling for a Bootstrap Dropdown by applying the max-height and overflow-auto classes:

<ul class="dropdown-menu max-height-200 overflow-auto" aria-labelledby="scrollingDropdown">
    <!-- Add a sufficient number of options to trigger scrolling -->
</ul>

How do you create a Bootstrap Dropdown with a specific width?

Set a specific width for a Bootstrap Dropdown by adding custom styles:

<div class="dropdown" style="width: 200px;">
</div>

Conclusion

The Bootstrap Dropdown Menu proves to be a versatile and feature-rich tool, offering developers a wide array of options to create intuitive and engaging navigation experiences. The concept of a Responsive Dropdown ensures a seamless user experience across devices, adapting to varying screen sizes and resolutions. The Dynamic Navigation Dropdown takes this adaptability further, providing interactive and context-aware navigation options that respond dynamically to user interactions.

The inclusion of Dynamic Content within dropdowns elevates their utility, enabling the presentation of interactive and ever-changing information directly within the navigation structure. The Select Menu feature enhances the user-friendliness of forms, providing a streamlined and accessible way for users to make selections. The diverse Navigation Options range from simple lists to multilevel structures, catering to a variety of content organization needs.

The commitment to aesthetics is evident in the Stylish Dropdown Design, ensuring that the menu not only serves a functional purpose but also contributes positively to the overall visual appeal of the website. The capability for Multilevel Dropdown Navigation offers a hierarchical organization, enhancing the user's ability to navigate through complex content structures.

Beyond the standard dropdown, the ability to Create Dropdowns within Buttons and integrate them seamlessly into Navbar Dropdowns provides additional flexibility for developers in designing interactive interfaces. The inclusion of features like Dropdown Menus with Headers and Dividers in Dropdowns adds organizational depth and visual clarity.

In the realm of alternative dropdowns, the Bootstrap Dropup Menu, Custom Dropleft Menus, and Dropright Navigation Components expand the possibilities for creating dynamic and visually appealing menus. The ability to Dynamically Add Menus via JavaScript enhances the interactive capabilities, allowing developers to respond to user actions in real-time.