Click Event is executed automatically

37 views Asked by At

I'm having this code

$(".menu").on('click', function(e) {
    e.preventDefault();
    $(this).addClass("open").children("div").slideDown(200);
});

$(document).on('click', ".menu.open", function(e) {
    e.preventDefault();
    $(this).removeClass("open").children("div").slideUp(200);
});

when I click the .menu the inner div slides down but it slides up again immediately and the open class is removed that's by only 1 click so how to fix this and make it work normal as a drop down menu for small screens opened by a click and closed by another click

2

There are 2 answers

0
brainless coder On BEST ANSWER

You are assigning the class open immediately on click and then sliding down-

$(".menu").on('click',function(e){
    $(this).addClass("open").........slideDown(200);
});

which is causing the delegated callback to be called. You should assign the class at the end of the animation and make sure you are not calling the open menu again -

$(".menu").on('click',function(e){
    var tthis = this; //saving the instance to refer in callback
    if ($(tthis).hasClass('open')){ //ignore if already open
         return;
    }
    $(tthis).children("div").slideDown(200, function(){
        $(tthis).addClass("open"); // add class at the end of the animation
    });
});

$(document).on('click',".menu.open",function(e){
    var tthis = this; //saving the instance to refer in callback
    $(tthis).children("div").slideUp(200, function(){
        $(tthis).removeClass("open"); // remove class at the end of the animation
    });
});
2
Scott Selby On

put

e.stopPropagation(); 

in both