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.
Use
.click(), and check the state of the element inside theclickhandler, using the:not(),:animated, and:visibleselectors, like this:This doesn’t rely on the state, which is a bit simpler 🙂