Search code examples
jqueryjquery-animatebindcssmousedown

How can I stop a jquery animation when mousedown is released?


Right now I have a simple button set up that animates when the mouse is pressed and reverses the effects of that animation when the mouse is released. The animation changes the 'top', 'left', and 'box-shadow' properties. I had to use a special jquery plugin in order to allow jquery's .animate() function to affect the element's box-shadow. For ease of reference, here is a GitHub repository of my current example.

The problem is, even if the mouse button is released immediately, the animation completes before it continues to reverse itself. The desired effect is for the user to control whether or not the button is moving "up" or "down" by holding or releasing the mouse button. See this example (last box on the right) to get an idea of what I'd like to achieve.

In my research so far, it seems that binding/unbinding should be used to accomplish this, but the examples I've seen didn't deal with stopping an animation before it had completed.


Solution

  • As you are using jQuery to animate stuff,

    You can use .stop() to

    Stop the currently-running animation on the matched elements.

    OR

    You can also use .finish() to

    Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.

    Then you can revert back to element's original values as the animation has stopped.