Skip to content Skip to sidebar Skip to footer

Button That Displays And Hides A Sliding Menu

I'm trying to build a header with a menu button that triggers a sliding menu. I can make the menu appear when I press the button, but I also want it to dissappear when I click the

Solution 1:

Like DeeMac said, it may be better to do this with css transition instead of jQuery animate. But just to add an option, I'll try to show you how to get this to work with jQuery animation also.

First of all, instead of inspecting if the animation is still running or not, you can just stop the ongoing animation before starting another. It will make the button to respond immediately to the users clicks.

For finding out if the menu is open or not, you can use toggleClass. This way you can just use hasClass to determine in which direction you need to animate the menu.

So, this what I came up with:

$('#nav-button').click(function () {
    $("#slidermenu").stop();

    animateToPosition = "0px";
    if ($("#slidermenu").hasClass("open")) {
        animateToPosition = "-300px";
    }

    $("#slidermenu").toggleClass("open");

    $("#slidermenu").animate({
        right: animateToPosition
    }, 200);

});

I made a Demo. If you are going with the css solution, it's fine. Maybe this will help someone else in the future.

Post a Comment for "Button That Displays And Hides A Sliding Menu"