$("#div1, #div2").fadeIn('500',function(){
{
console.log('Test');
}
});
Fiddle here: /
The above code will print 'Test' two times in the console. How can I make it print only one time. Is it possible?
$("#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?
Share Improve this question asked Apr 8, 2013 at 14:52 user2257938user2257938 6 | Show 1 more comment3 Answers
Reset to default 27Sure, 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
Working Demo
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;
});
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');
}
});
fadeIn
needs to be aString
("slow" or "fast") or aNumber
(representing the milliseconds the animation should take to complete). Passing "500" will just use the default400
milliseconds since it's aString
. – Ian Commented Apr 8, 2013 at 15:05