2

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') }; 
6
  • when do you want it fired? When the last fadeOut completes? When the first one does? Commented Jul 15, 2013 at 9:37
  • Why is it firing 16 times? Are you using the #open several times? Commented Jul 15, 2013 at 9:38
  • Well the best way would be bug-fix to stop it firing 16 times, but you could also just add a count variable and check it is 0 before firing Commented Jul 15, 2013 at 9:38
  • I know if I put in $('.a, .b, .c, .d').fadeOut() callback will fire 4 times, I guess maybe because it select 4 item fadeout than call fire 4 times. Commented Jul 15, 2013 at 9:39
  • 1
    The solution posted by asifsid88 is what I was describing Commented Jul 15, 2013 at 9:42

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

(+1) adding knowledge. Awesome... :)
0

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++; }); }); }); 

Comments

0

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') }; 

2 Comments

i can see, it wasn't when i was posting, sorry @JanDvorak