How to open 1 submenu and close others

My parent dropdowns are working perfectly. Like 1 open and when i click on 2nd the first one closes. But this is not working for submenus. All Submenu can be opened at once. But 1 want 1 sub menu at a time to be opened <script> document.addEventListener('DOMContentLoaded', function () { // Function to handle dropdown toggles function handleDropdownToggle(toggle) { toggle.addEventListener('click', function (event) { event.preventDefault(); // Prevent default link behavior var dropdownMenu = toggle.nextElementSibling; // Toggle visibility of the dropdown menu dropdownMenu.classList.toggle('show'); // Find the parent <li> with class .has-dropdown and add/remove the active class var parentLi = toggle.closest('li.has-dropdown'); if (parentLi) { if (dropdownMenu.classList.contains('show')) { parentLi.classList.add('active-dropdown'); parentLi.classList.remove('closed-dropdown'); } else { parentLi.classList.remove('active-dropdown'); parentLi.classList.add('closed-dropdown'); } } // Close other dropdown menus var otherDropdownMenus = document.querySelectorAll('.dropdown-menu.show'); otherDropdownMenus.forEach(function (menu) { if (menu !== dropdownMenu) { menu.classList.remove('show'); // Also remove the active class and add the closed class from other parent <li> elements var otherParentLi = menu.closest('li.has-dropdown'); if (otherParentLi) { otherParentLi.classList.remove('active-dropdown'); otherParentLi.classList.add('closed-dropdown'); } } }); }); } // Assuming you want to attach this to multiple toggles, you might do something like this: document.querySelectorAll('.dropdown-toggle').forEach(function(toggle) { handleDropdownToggle(toggle); }); // Get all dropdown toggles var dropdownToggles = document.querySelectorAll('.has-dropdown > .nav-link'); // Add click event listener to each dropdown toggle dropdownToggles.forEach(handleDropdownToggle); // Get all submenu toggles var submenuToggles = document.querySelectorAll('.dropdown-item > .nav-link'); // Add click event listener to each dropdown toggle // Add click event listener to each submenu toggle submenuToggles.forEach(function (toggle) { toggle.addEventListener('click', function (event) { var dropdownMenu = toggle.closest('.dropdown-menu'); dropdownMenu.classList.add('show'); // Close other dropdown menus var otherDropdownMenus = document.querySelectorAll('.dropdown-menu.show'); otherDropdownMenus.forEach(function (menu) { if (menu !== dropdownMenu) { menu.classList.remove('show'); } }); // Prevent event propagation to parent dropdown event.stopPropagation(); }); }); }); </script> I added a code above. I tried many thing from chatgpt but nothing work. I am trying from past 5 hours but nothing works as I want.

Comment (0)

You’ll be in good company