JQuery.toggle () to show and hide the submenu

I use this question code to make show / hide toggle

jQuery.toggle () to show and hide the submenu

$('#menu-lateral .sub-menu').hide(); //Hide children by default $('#menu-lateral > li > a').click(function() { event.preventDefault(); $(this).siblings('.sub-menu').slideToggle('slow'); }); 

The problem is that my submenu has its own submenu with many elements. Is there a way to adapt this code to work ALSO on the next level?

Important information: Wordpress does by default a child UL with the same class, so both are .sub menus.

how

 <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> </ul> </li> </ul> </li> </ul> 

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

Thanks for the help!

UPDATE: solution can 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) { event.preventDefault(); } $(this).siblings('.sub-menu').slideToggle('slow');}); 
+4
source share
1 answer

Yes, in this case, you can simply use the descendant selector - $('#menu-lateral li a') as your selector, rather than the direct selector you are using now - $('#menu-lateral > li > a') .

jsFiddle here.

Since you are using a descendant selector, all future "downstream" levels will be targeted individually in your expression $(this).siblings('.sub-menu').slideToggle('slow'); that will make it very easily extensible.

+2
source

Source: https://habr.com/ru/post/1490553/


All Articles