tibelchior tibelchior - 2 years ago 131
Javascript Question

jQuery .toggle() to show and hide a sub sub-menu

I'm using this question's code to make a show/hide toggle

jQuery .toggle() to show and hide a sub-menu

$('#menu-lateral .sub-menu').hide(); //Hide children by default

$('#menu-lateral > li > a').click(function() {

The problem is that my sub-menu has its own sub-menu with many items. Is there a way to adapt this code to work ALSO in the next level?

Important info: wordpress makes by default the child UL with the same class, so both are .sub-menu.


<ul id="menu-lateral" class="menu">
<li id="menu-item-29"><a href="#">Parent Level 1</a>
<ul class="sub-menu">
<li id="menu-item-108"><a href="#">Parent Level 2</a>
<ul class="sub-menu">
<li id="menu-item-104"><a href="#">Element</a></li>

Fiddle: http://jsfiddle.net/qfygM/1/

Thanks for the help!

UPDATE: The solution may be found here >> http://jsfiddle.net/qfygM/7/

Made by Zenith.

$('#menu-lateral .sub-menu').hide(); //Hide children by default

$('#menu-lateral li a').click(function(event){
if ($(this).next('ul.sub-menu').children().length !== 0) {

d.g d.g
Answer Source

Yes, in this case you could just use the descendant selector - $('#menu-lateral li a') as your selector as opposed to the direct child selector you're currently using - $('#menu-lateral > li > a').

jsFiddle here.

As you're now using the descendant selector, all future descending 'levels' will be targeted individually in your $(this).siblings('.sub-menu').slideToggle('slow'); statement, making it very easily extendable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download