antonscie antonscie - 2 months ago 10
jQuery Question

jquery each function for menu

hello guys i have a menu. i want to add a toogle animation to each parent menu.
but curently i stuck, because when i click the parent menu. all parent menu show their child menu.
i think i need a jquery each function, but i dont know how to implement with my case.
heres my code

$(".menu-item-has-children").prepend("<i></i>");
$(".menu-item-has-children").find("i").addClass("fa fa-plus-circle toogle-icon");
$(".toogle-icon").click(function(){
$(".sub-menu").slideToggle();
});


heres jsfiddle
https://jsfiddle.net/Lypj8tov/1/

Answer

Try:

$(".toogle-icon").click(function(){
  $(this).parent('.menu-item-has-children').find(".sub-menu").slideToggle();
});

Also you may simplify the whole thing:

$('<i class="fa fa-plus-circle toogle-icon"></i>')
  .click(function(){
    $(this).parent().find(".sub-menu").slideToggle();
  })
  .prependTo(".menu-item-has-children");

Check https://fiddle.jshell.net/ermakovnikolay/q5z4b64u/

Comments