Troubleshooting Bootstrap 5 dropdown display issue triggered by JavaScript

I am attempting to display a dropdown using JavaScript, but it appears there is an issue with Bootstrap 5. When trying to show the dropdown, an exception is thrown:

Uncaught TypeError: Cannot read property 'classList' of undefined at _e.show (dropdown.js:140)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="462429293235323427360673687668766b2423322775">[email protected]</a>/dist/css/bootstrap.min.css">
</head>

<body>

<div id="testDropdown" class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
        Dropdown button
    </button>
    <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
        <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
</div>

<div id="testModal" class="modal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Modal body text goes here.</p>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d4e4918a948a9489c6c1d0c597">[email protected]</a>/dist/js/bootstrap.bundle.min.js"></script>

<script>

    let testModal = document.getElementById("testModal");
    //new bootstrap.Modal(testModal).show(); //works

    let testDropdown = document.getElementById("testDropdown");
    new bootstrap.Dropdown(testDropdown).show(); //does not work

</script>

</body>
</html>

Is there a mistake on my end or is this a bug?

Thank you in advance.

Answer №1

It is recommended that the dropdown-trigger should be used instead of the parent dropdown...

<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" id="testDropdown" type="button" data-bs-toggle="dropdown"> Dropdown button </button>
    <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Action</a></li>
        <li><a class="dropdown-item" href="#">Another action</a></li>
        <li><a class="dropdown-item" href="#">Something else here</a></li>
    </ul>
</div>

Demo

Note: To trigger the dropdown from outside the dropdown's parent, Bootstrap 5 introduces a new auto-close option. Ensure that this is set to false in order to function correctly.

Answer №2

I managed to get it to work without the need for a button:

<!DOCTYPE html>
<html lang="en>

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1>

    <title>Dropdown Test</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="106874747f787b786b3150747c707b667429476775618573">[email protected]</a>/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="355754545f4c4f4d4f48664679757076704b21555446">[email protected]</a>/font/bootstrap-icons.css">
</head>

<body>

<div class="container-fluid>

    <div class="row justify-content-center>
        <div class="w-75 mt-2>

            <div class="input-group>
                <span class="input-group-text><i class="bi bi-search></i></span>
                <input type="text" class="form-control" placeholder="Search for something">
                <button class="btn btn-primary" type="button>Search</button>
            </div>

            <div class="dropdown>
                <div data-bs-toggle="dropdown" id="DROPDOWN_SEARCH></div>
                <div class="dropdown-menu w-100>
                    <a class="dropdown-item" href="#">Result 1</a>
                    <a class="dropdown-item" href="#">Result 2</a>
                    <a class="dropdown-item" href="#">Result 3</a>
                </div>
            </div>

        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f88e83838a85818ec88c828e8f92959d">[email protected]</a>/dist/js/bootstrap.bundle.min.js></script>

<script>
    let searchDropdown = new bootstrap.Dropdown("#DROPDOWN_SEARCH");
    searchDropdown.show();
</script>

</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing jQuery function through variable reference

My goal is to modify the jQuery function being used based on the value of a switch statement. In this scenario, I want to select the element and then apply the appropriate jQuery function depending on the 'direction' parameter. $('#'+t ...

Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)? var checks = document.querySelectorAll("ul li"); for (var i = 0 ...

Best Practices for Implementing JSON.stringify() with an AJAX Request

While I have a limited understanding of ajax and JSON, I am aware that using JSON.stringify in an ajax call can sometimes be beneficial. The ajax call below is functioning properly, whereas the one following it with the stringify method is not. I am unsure ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

What strategies can be used to efficiently perform Asynchronous Operations on a high volume of rows in a particular database table?

I am looking to perform Asynchronous Operations on every row of a specific database table, which could potentially contain 500,000, 600,000, or even more rows. My initial approach was: router.get('/users', async (req, res) => { const users = ...

Guide on how to indicate the specific sheet on a Google Sheets API node.js batchUpdate request

I need to insert a blank row above all the data on the second sheet, but I'm having trouble specifying the exact sheet. Right now, the empty row is being added to the first sheet. const request = { spreadsheetId: 'spreadsheetId', ...

The TextBox will alter its color following an incorrect submission

I am struggling to create a bootstrap form that will change the color of the borders to red after incorrect submission. The issue I am facing is that the textbox always remains in red. Does anyone have any suggestions for setting the textbox borders to red ...

Can you smoothly scroll to an anchor and stop the animation mid-scroll?

I've implemented a Jquery snippet that enables smooth scrolling to an anchor: <li><a href="#home">Home</a></li> which directs you to... <a name="home"></a> . var $root = $('html, body'); $('a&apo ...

Troubleshooting: Dealing with ng-click and invalid functions

Prior to resolving the issue, I encountered a component (within an HTML template) containing a ng-click that was invoking a nonexistent function. Is there a method to enable a strict mode (similar to 'use strict' in JS) or something equivalent t ...

What is the best way to specify a submission destination for a custom form component in Vue?

I am looking to streamline the use of a form component across my website, however, I need the submit button to perform different actions depending on which page calls the form-component. Experimenting with Vue components and data passing is new to me as I ...

Enhancing website performance with a combination of Google Analytics outbound click tracking and a JavaScript speed bump

I have successfully integrated the universal GA for tracking outbound clicks, however I have also added a "speed bump" pop-up message that appears when a user clicks on an offsite link. The JavaScript code for this is as follows: (specific to bank client - ...

As you scroll, the opacity gradually increases, creating a dynamic visual

Struggling to replicate a feature on a website where images gain opacity as you scroll down? Check out this site for reference: . While my current code somewhat achieves this effect, I'm having trouble figuring out how to apply a darker opacity gradua ...

Writing this SQL query in Sequelize

I am attempting to write this SQL query in my Sequelize controller, but I need to ensure that the data_time is within the last 30 days. SQL: SELECT * FROM bankapplication_transactions WHERE id_sender = 1 OR id_recipient = 1 AND data_time BETWEEN NOW() - ...

window.print function appears multiple times

Looking for help with a sample script I have that prints a section of my website page when a button is clicked. The issue arises when using ajax to transition and clicking the same button results in window.print activating multiple times. How can I ensur ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Passing a JavaScript object that may be undefined to a pug template in Node.js

My journey requires transferring a set of JavaScript objects to the pug template. router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeE ...

What is the best way to upload a file to a server while working with Vue.js in the Filemanager plugin, or how can I access a global function

How can I upload a file to the server using Vue.js in the Filemanager plugin? I have tried multiple methods and the console log shows that the upload was successful, but I am not able to see any files on the server. Does anyone know what could be wrong? & ...

The issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

Guidelines for leveraging AngularJS Decorators to deactivate a button within an Html document

Currently, I am utilizing the blur admin theme and exploring the possibility of using decorators to hide a button without directly modifying the HTML. Despite my efforts, I have been unable to successfully conceal the button. Can someone provide guidance o ...