Steve
Steve

Reputation: 143

Open/close a submenu by clicking

I wanted to make a menu when you click on a li that the chlildren div with the class .navi-submenu to have the class active.. then it is visible.. it works.. but it doesnt close anymore if i click a secound time... I think the statement is false.. could you help me?

$("#main-navi ul li").click(function(event){
    event.preventDefault(); 

    var i = $(this).children(".navi-submenu");

    if(i.hasClass("active")){
        i.removeClass("active");
    }else{
        i.addClass("active");
    }
});

Upvotes: 1

Views: 1365

Answers (1)

Milanzor
Milanzor

Reputation: 1930

Try using toggleClass()

$("#main-navi ul li").click(function(event){ event.preventDefault();
 $(this).find(".navi-submenu").toggleClass('active');
});

I've changed the function children() to find(), to me this feels more reliable, because it feels like children() looks for direct children, while find() looks at every element inside itself. That's not based on actual facts by the way, just a preference/gut feeling I guess.

Upvotes: 1

Related Questions