Moltas
Moltas

Reputation: 69

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 button again.

This is the event that triggers when the button is clicked.

$('#nav-button').click(function () {

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

    $("body").animate({right: "300px"}, 200);    

});

I looked up the animate method and saw that it has a function called done, which takes two parameters. A promise and a boolean. So I figured I can use a if-statement to check if the animation is done, and if the animation is done, the button would send the slidermenu back.

But how can I test if animate().done() is true? Or is there a more simple way of achiveing this?

Here is my fiddle.

Upvotes: 0

Views: 83

Answers (2)

balzafin
balzafin

Reputation: 1426

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.

Upvotes: 1

user1017882
user1017882

Reputation:

.is(':animated') will return true if it's currently being animated.

In the context of what you're trying to do:

if(!$('#slidermenu').is(':animated'))
{
  // Animation has finished
}

As an aside:

I try and do this with CSS only now where possible. If you use jQuery toggleClass and predefine the right attributes in your CSS for the toggled classes, you can add a CSS transition to deal with the animation. Just thought it was worth mentioning (this does come with it's own compatibility issues).

Upvotes: 2

Related Questions