Search code examples
javascriptjqueryanimationnavigationhamburger-menu

HowTo: First click animation 1, second click animation 2



I am about to build a mobile burger menu that animates as follows:

1) Click 1 on burger menu: menu open animation...nav links fade-in last
2) Click 2 on burger menu: nav links fade-out first...menu close animation

I am animating with jQuery:

/* mobile menu fx */
$(document).ready(function(){

    $('#nav-icon4').click(function(){
        $(this).toggleClass('open');
        $('#mobile-menu').toggleClass('open');
        $('#mobile-menu-elements').toggleClass('open');
        $('#mobile-menu-blurredBg').toggleClass('open');
        $('#mobile-menu-elements-ul').toggleClass('open');
    });

});

How can I set a different class for the second click (closing the menu)?


Solution

  • If you want to do it in the JS side, why dont you try to add a count variable, see if it works:

    /* mobile menu fx */
    $(document).ready(function(){
    
        var count = 0;
    
        $('#nav-icon4').click(function(){
           if(count == 0){
               // do something in the first click;
               count++;
           } else{
               // do something in the second click;
                count=0;;
           }
        // Dont know which one goes in the first or in the second click
        $(this).toggleClass('open');
        $('#mobile-menu').toggleClass('open');
        $('#mobile-menu-elements').toggleClass('open');
        $('#mobile-menu-blurredBg').toggleClass('open');
        $('#mobile-menu-elements-ul').toggleClass('open');
        });
    
    });
    

    I know it's a bit dirty and there could be better ways. I haven't checked if it works, but this is just one of them, hope it helps.