Chris
Chris

Reputation: 2035

Prevent Javascript from being executed twice

I have a script that I am developing that creates a sliding button type effect. Five div's are situated next to eachother each with a link. When one of those DIVS are clicked on the associated content is expanded and the rest of the Div's are closed.

The problem is, if a user clicks the Div twice while it loads or clicks another Div in rapid succession, cracks start to show.

I am wondering if it would be possible to only allow the query to be executed once and wait until completion rather than queuing it.

Here is my current code, if it is crap feel free to comment on how I could better it... I am not the best at Javascript/jQuery :P

    function mnuClick(x){
    //Reset all elements
    if($('#'+x).width()!=369){
        $('.menu .menu_Graphic').fadeOut(300);
        $('.menu_left .menu_Graphic').fadeOut(300);
        $('.menu_right .menu_Graphic').fadeOut(300);
        $('.menu').animate({width: "76px"},500);
        $('.menu_left').animate({width: "76px"},500);
        $('.menu_right').animate({width: "76px"},500);
    }
        var ElementId = '#' + x;

        $(ElementId).animate({
            width: 369 + "px"
        },500, function(){ 
            $(ElementId + ' .menu_Graphic').fadeIn(300);
        });
}

Thanks in advance, Chris.

Upvotes: 6

Views: 9165

Answers (5)

Brad Christie
Brad Christie

Reputation: 101594

Quick answer: use .addClass and .removeClass and test for the existence of the class at execution time. Test if it's set and return, or add it, execute the code, then remove it.

Upvotes: 1

Axarydax
Axarydax

Reputation: 16603

you can unplug the onClick event handler (mnuClick) when the event starts, to effectively disable invoking the mnuClick twice, but be sure to restore it when the event ends.

Upvotes: 1

Oliver M Grech
Oliver M Grech

Reputation: 3171

you can create an invisible maskin and maskout ( like the background in lightbox etc ) or disable clicks until the animation finishes.

Upvotes: 0

fcalderan
fcalderan

Reputation:

(function() {
var mutex = false;

    function mnuClick(x){
        if (!mutex) {
           mutex = !mutex;

           /* all code here ...   */

           mutex = !mutex; /* this statement should go into animation callback */
        }

    }

})();

mantain a state through a variable so you cannot click more than once until code has fully executed

Upvotes: 3

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

You need a "isRunning" flag. Check for it before you start. Set it when you start the sequence, clear it when it ends.

Upvotes: 9

Related Questions