Is there an easier way to chain different jQuery actions for different selectors and then nested $ .when?

In jQuery, you can easily chain actions for the same selector, but if you want to use a different selector for each action that requires a nested $.when with more than two actions that are pretty hard to read and maintain.

HTML:

 <span id='a'>Hello</span> <span id='b'>world</span> <span id='c'>!!!</span> 

CSS

 span { display: none; } 

JS: based on this: how to hide multiple elements, but only call the handler once?

 var d = 500; // duration // Execute in parallel. //$('#a').show(d).hide(d); //$('#b').show(d).hide(d); //$('#c').show(d).hide(d); $.when($('#a').fadeIn(d).fadeOut(d)).done(function () { $.when($('#b').show(d).hide(d)).done(function () { $('#c').slideDown(d).slideUp(d); }); }); 

jsfiddle (old)

jsfiddle-2

I could use a queue , but it seems to work only for the same selector.

Is there a way to write it in a more convenient way, for example:

pseudo code

 var myActions = []; myActions.push(function(){...}); myActions.push(function(){...}); myActions.push(function(){...}); something.executeSequentially(myActions); 

EDIT:

I updated the demo to make it a little more complicated.

+5
source share
2 answers

If you really don't need to run into errors (and this is hardly possible with animation, I suppose), you can use the following approach (kudos to @Esailija, since this solution is basically a simplified version of its answer ):

 var chainOfActions = [ function() { return $('#a').fadeIn(d).fadeOut(d); }, function() { return $('#b').fadeIn(d).fadeOut(d); }, function() { return $('#c').fadeIn(d).fadeOut(d); }, ]; chainOfActions.reduce(function(curr, next) { return curr.then(next); }, $().promise()); 

Demo There are three key points here:

  • each function in the action chain already returns a promise (if not, you can promise it by returning the result of a call to .promise() )
  • a chain is created at each reduce step, since each callback passed to then() creates a new promise
  • the whole chain is started by making an empty promise as the initial value of the reduce battery.
+4
source

Change, update

 var d = 500 , something = {} , myActions = []; myActions.push( function (next) { $('#a').fadeIn(d).fadeOut(d, next) }); myActions.push( function (next) { return $('#b').show(d).hide(d, next) }); myActions.push( function () { return $('#c').slideDown(d).slideUp(d) }); something.executeSequentially = function (arr) { return $(this).queue("fx", arr); }; something.executeSequentially(myActions); 

jsfiddle http://jsfiddle.net/guest271314/2oawa1zn/

+1
source

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


All Articles