How to increase animation delay on each pass of the for loop

First, I created a basic demo of what I have here right now .

Secondly, this is the javascript that I use.

var boxes = ["#one","#two","#three","#four"]; boxhover = function(a){ $("#hover").hover( function(){ $(a).stop(true).delay(250).animate({opacity:1}); }, function(){ $(a).stop(true).delay(250).animate({opacity:0}); } ) } for(var i=0; i<boxes.length; i++) { boxhover(boxes[i]) } 

What I hope to achieve is that each box is pointing at each other one after another with a delay time of 250. I tried to add a delay to the animation function (as you can see above), as well as setTimeout in a for loop, but not lucky. Any help would be great.

+6
source share
1 answer

You can pass the index of the array as an additional parameter to your boxhover function, and then multiply by the delay factor.

 var boxes = ["#one","#two","#three","#four"]; boxhover = function(a, i){ $("#hover").hover( function(){ $(a).stop(true).delay(250 * i).animate({opacity:1}); }, function(){ $(a).stop(true).delay(250 * i).animate({opacity:0}); } ) } for(var i=0; i<boxes.length; i++) { boxhover(boxes[i], i) } 

jsfiddle

Alternative solution:

To avoid binding multiple hover event handlers to #hover and having to maintain an array of identifiers, you can do the following:

 $("#hover").on({ 'mouseenter': function(e) { // Animate the box set to visible animateBoxSet(1); }, 'mouseleave': function(e) { // Animate the box set to invisible animateBoxSet(0); } }); function animateBoxSet(opacity) { // For each box $('.box').each(function (index, element) { // Set the delay based on the index in the set var delay = 250 * index; // Animate it the visibility after the delay $(element).stop(true).delay(delay).animate({ 'opacity': opacity }); }); } 

jsfiddle

+3
source

All Articles