Skip to content

Instantly share code, notes, and snippets.

@tomviner
Last active December 19, 2015 19:59
Show Gist options
  • Save tomviner/6010366 to your computer and use it in GitHub Desktop.
Save tomviner/6010366 to your computer and use it in GitHub Desktop.
Note to everyone using any type of "click performs an animation"

Note to everyone using any type of click performs an animation:

While slowing down an animation, we just found that it's really easy to make code fail when you click to trigger an animation multiple times while it's still performing the previous rounds. This is due to the variables we're using getting all out of sync as you end up running the animation code multiple times concurrently. Sad times.

The solution is to call $('.item-that-is-animating').stop(true, true); within the click handler before you do your animation code. This Stops the currently-running animation on the matched elements. and the true arguments are for clearQueue ie delete any events waiting to be triggered and jumpToEnd which, critically, will run your callback immediately without waiting for the delay to finish.

Example:

$("#visual_type_selector").delegate("a", "click", function() {
    var newHash = $(this).attr('href');
    $('.visualisation .graph').stop(true, true);
    $('.visualisation .'+currentHash).fadeOut(200, function(){
        $(".visualisation ."+newHash).fadeIn(200, function(){currentHash=newHash});
    })
});

Putting the .stop in there means that the currentHash is always updated, even if the 200ms hasn't finished when the new click is triggered.

Result: click as fast as you like, you can't break the page. Fun times!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment