Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery slideToggle menus that collapses sibling menus before opening/closing itself

Here's a crude sample of what I'm dealing with: http://jsfiddle.net/dX2ux/1/

A client's in-house developed CMS dynamically creates menus using this HTML structure. It also comes with the jQuery script that is shown on the sample.

I want to edit the script so that it closes it's sibling's open menus before it toggles itself open. The show class is has to be toggled as well.

So far, I've come up with this: http://jsfiddle.net/dX2ux/2/

But if you play with it, it screws up when you click one of the sub menus.

Can anyone shed some light on how I might achieve the behavior I'm aiming for? Also, is this the best way to do it? Am I overthinking this?

Any help is appreciated. Thank you.

like image 559
clueless Avatar asked Oct 22 '22 17:10

clueless


1 Answers

Not really sure if this is the "best" way per se, but with that kind of markup, this solution should work:

$('.toggle-menu').on('click',function(e){
    e.preventDefault();
    $(this).parent().siblings().children('.toggle-menu').removeClass('show').next().slideUp();
    $(this).toggleClass('show').next().slideToggle();
});

Edited your fiddle to show the effect: http://jsfiddle.net/dX2ux/3/

like image 177
rgin Avatar answered Oct 24 '22 10:10

rgin