tags:

views:

27

answers:

1

I have a menu that is toggled when a user selects a link. The menu had different show and hide animations attached, and I want to prevent toggling while the animation is running. The following snippet works, but flips the state of toggle if the link is clicked quickly twice (i.e. if the user clicks the link quickly twice, the next click will trigger the same action):

<a href="" id="button">Menu</a>
<div id="menu">...</a>

<script>
$("#button").toggle(
    function (e) { 
      if $("#menu").is(":animated")) return false;
      $("#menu").show("drop", {}, "slow"); 
    }, 
    function (e) { 
      if ("#menu").is(":animated")) return false;
      $("#menu").hide("bounce", {}, "slow"); 
    }
);
</script>

How can I prevent switching states within toggle?

Thanks.

+2  A: 

Use .click(), and check the state of the element inside the click handler, using the :not(), :animated, and :visible selectors, like this:

$("#button").click(function () { 
  var menu = $("#menu:not(:animated)");
  if(menu.is(":visible")) menu.hide("bounce", {}, "slow");
  else menu.show("drop", {}, "slow"); 
});

This doesn't rely on the state, which is a bit simpler :)

Nick Craver
Nick does it again!
Mark Schultheiss
@Mark Schultheiss: Question changed though, updating...
Nick Craver
Hi Nick. Sorry I forgot to mention that I am running different show and hide animations. Any ways to add support for this?
Kevin Sylvestre
@Kevin: Updated, check it out, this checks for the state inside the click, rather than the state of the functions themselves.
Nick Craver
@Nick Thanks! Sorry again for the confusion.
Kevin Sylvestre