jQuery prevent multiple clicks until animation is done

jquery

Solution

One way to do this is to keep track of if an animation is currently active. Here is a simple way to do this: http://jsfiddle.net/QCWgR/

var active = false;

$(".flow-chart img").click(function () {
    if (active) {
        return;
    }
    active = true;        
    var div_class = $(this).data("class");

    $(".hide_show:visible").fadeOut('slow', function() {
        // note the callback that sets active to false at end of animation
        $("."+div_class).fadeIn("slow", function() { active = false; });
    });

});

With this approach, the first click has to complete the animation cycle before the next one will happen.

Using closure to keep active out of global namespace

To keep active out of global namespace you can run the whole block inside an anonymous closure like so:

http://jsfiddle.net/QCWgR/2/

(function () {
    var active = false;

    $(".flow-chart img").click(function () {
        if (active) {
            return;
        }
        active = true;        
        var div_class = $(this).data("class");

        $(".hide_show:visible").fadeOut('slow', function() {
            $("."+div_class).fadeIn("slow", function() { active = false; });
        });

    });
})();​

Problem

Currently I have something setup where a user clicks on an image and based off that image, a div will fade in / fade out. If the user goes crazy and clicks on a bunch of the images at the same time, multiple divs load rather than just the last requested one. I've tried to illustrate my problem here. http://jsfiddle.net/BBgsf/ Clicking on any of those images will load the corresponding div with the number. But if you click on different images before the animation is completed, it loads the other divs as well. jQuery ``` $(".flow-chart img").click(function () { var div_class = $(this).data("class"); $(".hide_show:visible").fadeOut('slow', function() { $("."+div_class).fadeIn("slow"); }); }); ``` HTML ``` <div class="1 hide_show">1</div> <div class="2 hide_show" style="display: none">2</div> <div class="3 hide_show" style="display: none">3</div> ``` How can I prevent the multiple divs from loading rather than just one at a time? ​

Original source