Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery fadeIn runs twice in its callback

var counter = 0;
jQuery("#div1, #div2").fadeIn('300',function(){
{
    counter++;
    console.log(counter);
}

The code above will print "1" and "2" since the jQuery fadeIn is implied on two different DOM objects. Is there anyway to cause it to run only once without breaking this code?

like image 576
Alon Avatar asked Oct 21 '12 14:10

Alon


4 Answers

A simple solution :

$("#div1").fadeIn(300);
$("#div2").fadeIn(300,function(){
   // do something only once
});

The cleanest solution is to use jQuery's promise system :

$.when($("#div1, #div2").fadeIn('300')).done(function(){
   // do something only once
});

demonstration

like image 167
Denys Séguret Avatar answered Nov 19 '22 15:11

Denys Séguret


It's a quick solution but not the best

var myFlag = true;
jQuery("#div1, #div2").fadeIn('300',function(){
{
    if(myFlag == true)
    {
        // write the code here
        myFlag = false;
    }
}

Hope this helps... Muhammad.

like image 22
Muhammad Reda Avatar answered Nov 19 '22 13:11

Muhammad Reda


You are explicitly telling it to run twice because you've defined a selector of two items. If you want it to run once, ask it to run on one item:

jQuery("#div1")
like image 4
Paul Fleming Avatar answered Nov 19 '22 15:11

Paul Fleming


In terms of sequencing your code:

jQuery("#div1, #div2").fadeIn('300',function(){
    counter++;
    console.log(counteR);
});

Is the same as

jQuery("#div1, #div2").each(function(){
   jQuery(this).fadeIn('300',function(){
        counter++;
        console.log(counteR);
    } );   
})

SO your callback will fire for each element

like image 2
charlietfl Avatar answered Nov 19 '22 14:11

charlietfl