Delayed Bootstrap Dropdown Closing

by Osama Qassar

HTML

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-expanded="false">
    Dropdown button
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <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>

<!-- Bootstrap JS (Optional if you want dropdown functionality) -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>

JavaScript

document.addEventListener("DOMContentLoaded", function() {
  var dropdownMenu = document.querySelector('.dropdown-menu');
  var dropdownButton = document.querySelector('.dropdown-toggle');

  dropdownMenu.addEventListener('click', function(event) {
    // Prevent closing the dropdown when clicking inside it
    event.stopPropagation();
  });

  dropdownButton.addEventListener('click', function() {
    var isOpen = dropdownMenu.classList.contains('show');
    if (!isOpen) {
      // Open the dropdown if it's not already open
      dropdownMenu.classList.add('show');
    } else {
      // Close the dropdown after a delay of 1 second (1000 milliseconds)
      setTimeout(function() {
        dropdownMenu.classList.remove('show');
      }, 1000);
    }
  });

  // Close the dropdown when clicking outside of it
  document.addEventListener('click', function(event) {
    var isDropdown = event.target.closest('.dropdown');
    if (!isDropdown) {
      dropdownMenu.classList.remove('show');
    }
  });
});