I have this Javascript code snippet that deals with expanding and collapsing submenu items:
<script type="text/javascript>
jQuery(function(){
jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){
var current=jQuery(this).next();
var grandparent=jQuery(this).parent().parent();
if(jQuery(this).hasClass('left-caret')||jQuery(this).hasClass('right-caret'))
jQuery(this).toggleClass('right-caret left-caret');
grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
grandparent.find(".sub-menu:visible").not(current).hide();
current.toggle();
e.stopPropagation();
});
jQuery(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
var root=jQuery(this).closest('.dropdown');
root.find('.left-caret').toggleClass('right-caret left-caret');
root.find('.sub-menu:visible').hide();
});
});
</script>
The above script works with HTML code like this:
<li class="dropdown-submenu submenu">
<a class="trigger right-caret">Category Name</a>
<ul class="dropdown-menu submenu">
<li>Subcategory</a></li>
</ul>
</li>
However, I am facing an issue where when I click on one submenu item to expand it, the previously opened ones remain open. The only way to collapse them is by clicking on each individually. Can anyone help me modify the JavaScript code to automatically collapse other submenu items when a new one is expanded?
This is just a simplified example - in reality, the subcategory list is generated dynamically using a foreach loop.
Here is a sample scenario: