Home > Net >  Bootstrap dropdown event not firing
Bootstrap dropdown event not firing

Time:09-02

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:

  1. Add event listeners on the .dropdown-menu’s parent element. in your case .dropup

  2. 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>

  • Related