Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide multiple elements with jQuery and get one callback

The question is pretty straightforward. If I select two or more elements with jQuery and, for example, use jQuery's fadeOut() function to hide them, the callback function is invoked twice (for each element). Is there a way to only receive one callback?

The code I am currently using to perform this task is pasted below.

$('#element-1, #element-2').fadeOut( 250, function() { /* Callback invoked twice. */ });

A similar question has been posted before (jQuery multiple animate() callback), but the solution seems quite complicated for what seems a simple problem.

like image 367
Bart Jacobs Avatar asked Sep 11 '11 13:09

Bart Jacobs


1 Answers

You can use $.when [docs] (deferred objects):

$.when($('#element-1, #element-2').fadeOut(250)).then(function() {
    // do something
});

DEMO

This works with any animation afaik.

like image 87
Felix Kling Avatar answered Oct 23 '22 12:10

Felix Kling