Bootstrap 5 Menu Drop Down and Navigate


// The drop down menu needs to allow for navigation to parent as well as drop down.
// This javascript will find all instances of .dropdown-toggle (parent menu items) and if there is
// a .show class (ie; the submenu is showing), it will change to default behaviour (href navigation).
// If no .show class, bootstrap behaviour should be activated. // Target all parent menu items with a dropdown-toggle
const dropdownToggles = document.querySelectorAll('.dropdown-toggle');
dropdownToggles.forEach(function(dropdownToggle) {
const dropdownMenu = dropdownToggle.nextElementSibling; // Get the corresponding dropdown menu
const dropdown = dropdownToggle.closest('.dropdown'); // Get the closest dropdown container // Manually track the dropdown visibility state let isDropdownVisible = false; // Attach the click event to each parent link dropdownToggle.addEventListener('click', function(e) { e.preventDefault(); // Prevent Bootstrap's default behavior of toggling the dropdown if (isDropdownVisible) { // If the dropdown is open, navigate to the link window.location.href = dropdownToggle.href; // Navigate to the href } else { // If the dropdown is not open, show it and prevent navigation const bsDropdown = new bootstrap.Dropdown(dropdownToggle); bsDropdown.show(); // Explicitly show the dropdown without navigating // Update our manually tracked state isDropdownVisible = true; } });

});