I'm trying to fire a function when a bootstrap dropdown-menu
is hidden, here's the code I tried:
jQuery(document).ready(function($) {
$(".dropdown-menu").on("hidden.bs.collapse", function(e) {
console.log(e);
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.rtl.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<button type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropup
</button>
<ul >
<li><a href="#">Menu item</a></li>
<li><a href="#">Menu item</a></li>
<li><a href="#">Menu item</a></li>
</ul>
</div>
Nothing is being written to console, what am I doing wrong?
Thanks!
CodePudding user response:
Add event listeners on the .dropdown-menu’s parent element. in your case
.dropup
You need to use
hidden.bs.dropdown
. The.collapse
you have used is for Nav's
jQuery(document).ready(function($) {
$(".dropup").on("hidden.bs.dropdown", function(e) {
console.log(e);
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.rtl.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<button type="button" data-bs-toggle="dropdown" aria-expanded="false">
Dropup
</button>
<ul >
<li><a href="#">Menu item</a></li>
<li><a href="#">Menu item</a></li>
<li><a href="#">Menu item</a></li>
</ul>
</div>