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?
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
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.
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")
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With