How to hide several elements, but only once to call the handler?

I hide a few elements like this:

$('#item1,#item2,#item3').hide('slow',function() { console.log('hidden'); }); 

The problem is that these magazines are four times. For reasons beyond my control, I cannot use a common class for each element. Is there a good jquery-ish way to make this handler only fire after the last element is hidden? (or first, since they should be almost simultaneous)

In addition, the elements will be hidden and shown many times, so everything that is used to limit the invocation of the handler must be reset subsequently.

I can obviously put some kind of boolean in the handler, but I was hoping for a cleaner solution.

+2
source share
4 answers

You can use $. when () and deferred.done ()

 $.when($('#item1,#item2,#item3').hide('slow')).done(function() { console.log('hidden'); }); 

Simple working example

+4
source

What about...

 $('#item1,#item2,#item3').hide('slow', function() { if ($(this).is(':last')){ // code } }); 

EDIT: it does not work because the context of $(this) changes inside the hide() callback. First try caching:

 var $els = $('#item1,#item2,#item3'); $els.hide('slow', function(e) { if ($(this).is($els.last())){ alert('test'); } }); 
+3
source

You can use a queue (although @ManseUK's answer looks like the right way to do it now)

 $({}) .queue(function(next){ $('#item1, #item2, #item3').hide('slow', next); }) .queue(function(){ console.log('hidden'); }); 

demo at http://jsfiddle.net/duzB8/

+1
source
 var counter = 0; $('#item1,#item2,#item3').hide('slow',function() { counter++; if ( counter == 3 ){ console.log('hidden'); } }); 
0
source

Source: https://habr.com/ru/post/1207951/


All Articles