Daniel Williams Daniel Williams - 7 months ago 13
Javascript Question

Can't get Bootstrap dropdown function to fire after open

I've set up my code to run an alert upon the Bootstrap menu being opened, but I'm struggling to get the alert to fire.



$('.dropdown.data-api').on('shown.bs.dropdown', function () {
alert('it worked!');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


<div class="dropdown">

<span data-toggle="dropdown">Click me</span>

<ul class="dropdown-menu">
<li>Hello World!
</ul>

</div>




Answer

The event selector is looking for a dropdown with both dropdown and data-api classes. Either remove the .data-api from the event selector, or add data-api to the dropdown class list.

$('.dropdown.data-api').on('shown.bs.dropdown', function () {
   alert('it worked!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<div class="dropdown data-api">
    	
    <span data-toggle="dropdown">Click me</span>

    <ul class="dropdown-menu">
        <li>Hello World!
    </ul>
    	
</div>

Comments