Help! My jQuery function runs twice (or more)!

I’ve run into this problem a few times. I get a nice slideUp() and slideDown() action going, and the slide happens twice on each click. I couldn’t figure it out because the listeners were only set up once, so should only run once, right?

jQuery ('.button').click (function (e) {
    e.preventDefault ();

    jQuery ('.slide-areas').slideUp (300, function, () {
        jQuery ('#my-slide-area').slideDown (300);
    });
});

Actually I found out that no, that’s not always the case. What happens is that the callback function is run once for every element that’s found. So if you have two elements it will run twice. If you have three elements it will run three times.

OK, that’s all well and good, but how do you stop that from happening???

It turns out that jQuery actually helps you with this. You need to use a promise() and done() as well. That will ensure that the callback function is run only once when everything is actually done.

The final code looks like this:

jQuery ('.button').click (function (e) {
    e.preventDefault ();

    jQuery ('.slide-areas').slideUp (300).promise ().done (function, () {
        jQuery ('#my-slide-area').slideDown (300);
    });
});

And that’s all there is to it! Simple when you know…

Leave a Reply

Your email address will not be published. Required fields are marked *