Reputation:
$("#div1, #div2").fadeIn('500',function(){
{
console.log('Test');
}
});
Fiddle here: http://jsfiddle.net/y97h9/
The above code will print 'Test' two times in the console. How can I make it print only one time. Is it possible?
Upvotes: 8
Views: 507
Reputation: 14827
Sure, you can use jQuery promise to solve multiple callbacks problem:
$("#div1, #div2").fadeIn('500').promise().done(function()
{
console.log('Test');
});
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
Upvotes: 27
Reputation: 1
Use a boolean flag to prevent console.log('Test'); from being called twice.
var isCalled = false;
$("#div1, #div2").fadeIn('500',function(){
if(!isCalled) {
isCalled = true;
console.log('Test');
}
});
Upvotes: -1
Reputation: 39659
The callback will run once for every matched element. You can always set a flag to see if it's been run already though:
var hasRun = false;
$("#div1, #div2").fadeIn('500', function() {
if (hasRun) return;
console.log('Test');
hasRun = true;
});
Upvotes: 3