javascriptjquerywordpressslidetoggle

Collapsible list - Collapsing multiple list items with separate toggles


I found some jquery code to be able to have a collapsible sub menu in a list.

When I apply this code:

$('.menu-item-has-children').prepend('<a id="fa-menu" href="#"><i class="fa fa-plus"></i></a>');
$("#fa-menu").on("click", function(){
    $(".sub-menu").slideToggle();
    $(this).toggleClass("active");
});

I am able to expand and collapse, but it does so for every instance of .sub-menu and only allows me to toggle with the first #fa-menu instance.

See my website for an example.

How do I get it to toggle separate from one another.


Solution

  • Instead of $(".sub-menu").slideToggle(); Use $(this).parent().find(".sub-menu").slideToggle();, Call preventDefault() if you want to stop propagation.