user1575921
user1575921

Reputation:

execute function not more than one time

I wrote the code shown below to call lightbox show and callback some function, for example function_a, but it will fire 16 times.

How can I make it fire only once?

$("#open").click(function(){
    $('.a, .b, .c, .d').fadeOut(600,function(){
        $('.e, .f, .g, .h').fadeIn(400,function(){
            function_a();
        });
    });
});

function_a(){
    console.log('fire')
};

Upvotes: 2

Views: 94

Answers (3)

David Hellsing
David Hellsing

Reputation: 108480

You can use $.fn.promise, f.ex:

$("#open").click(function(){
    $('.a, .b, .c, .d').fadeOut(600).promise().done(function(){
        $('.e, .f, .g, .h').fadeIn(400).promise().done(function(){
            function_a();
        });
    });
});

From the docs:

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended.

Also note that classNames must be at least 2 characters long.

Upvotes: 5

Pash Shocky
Pash Shocky

Reputation: 66

try this:

var fired = 0; 
$("#open").click(function(){
    $('.a, .b, .c, .d').fadeOut(600,function(){
        $('.e, .f, .g, .h').fadeIn(400,function(){
            if (fired < 1) function_a();
            fired ++;
        });
    });
});

function_a(){
    console.log('fire')
};

Upvotes: 0

asifsid88
asifsid88

Reputation: 4701

This is because you may have 16 elements which class having those specified
Have a variable to keep the track of it

$("#open").click(function(){
    var iCount=0;
    $('.a, .b, .c, .d').fadeOut(600,function(){
        $('.e, .f, .g, .h').fadeIn(400,function(){
            if(iCount==0)
               function_a();
            iCount++;
        });
    });
});

Upvotes: 0

Related Questions