We help IT Professionals succeed at work.

J Query Toggle sub menus not working as desired

Robert Granlund
on
I have a function that toggles a sub-menu when the parent is clicked.  This works fine.  However, if I click on another menu choice (parent) the sub-menu toggles open but the prior sub-menu that was toggled open stays open.  What I want is for each toggled sub-men closes if another parent is clicked so only one sub-menu is open at a time.

$("#menu-mobile .sub-menu").hide();
   
$('#menu-mobile').children().click(function(){
    $(this).children('.sub-menu').slideToggle('slow'); 
});

Open in new window

Comment
Watch Question

ZvonkoSystems architect
CERTIFIED EXPERT
Top Expert 2006

Commented:

You mean this:


$("#menu-mobile .sub-menu").hide(); 
    
$('#menu-mobile').children().click(function(){ 
   $("#menu-mobile .sub-menu").hide(); 
   $(this).children('.sub-menu').slideToggle('slow');  
});
Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
$("#menu-mobile .sub-menu").hide();
   
$('#menu-mobile').children().click(function(){
    $(".this-menu-is-now-fully-opened").slideUp("fast", function() {
           $(this).removeClass("this-menu-is-now-fully-opened");
    });
    $(this).children('.sub-menu').slideToggle('slow', function() {
             $(this).addClass("this-menu-is-now-fully-opened");
    }); 
});

Open in new window