user1374796
user1374796

Reputation: 1582

jQuery: index slice function in iterations

I have a slice function set up, calling the index of a .test to fade in the .test divs in blocks of 5. There's a demo here: http://jsfiddle.net/neal_fletcher/JT4KB/2/
jQuery:

$(document).ready(function () {
    $('.test').each(function (index) {
        $('.test').slice(0, 5).delay(500).fadeIn(300);
        $('.test').slice(5, 10).delay(1000).fadeIn(300);
        $('.test').slice(10, 15).delay(1500).fadeIn(300);
    });
});

This works fine, but as the site will be content managed I want a more compact solution, thus instead of having to write a function for every 5 divs, is there a way to call this function by adding an extra 500 onto the delay for every 5 divs? If that makes sense? Any suggestions would be greatly appreciated!

Upvotes: 0

Views: 97

Answers (3)

georg
georg

Reputation: 215009

You can add a new method to jQuery like this:

$.fn.eachSlice = function(size, callback) {
    var $t = $(this);
    for(var i = 0; i < $t.length; i += size) {
        callback.call($t.slice(i, i + size).get(), i / size);    
    }
    return $t;
}

and then

$(".test").eachSlice(5, function(sliceIndex) {
   $(this).delay(sliceIndex * 500).fadeIn();
});

http://jsfiddle.net/JT4KB/16/

Upvotes: 0

Nick Avi
Nick Avi

Reputation: 1239

Here you go sir.

http://jsfiddle.net/JT4KB/17/

$(document).ready(function () {
    setTimeout(function () {
       $('.test').each(function (i) {
         var delay = Math.floor(i/5)*500 + 500;
         $(this).delay(delay).fadeIn(300);
       });
    }, 1000);
});

Upvotes: 2

Laurens
Laurens

Reputation: 2607

You can use a loop to achieve this. This loop has to loop 'the number of .test divs'/5 times:

$(document).ready(function () {
    setTimeout(function () {
        for (i=0; i<=$('.test').length/5; i++) {
            $('.test').slice(5 * i, 5*(i+1)).delay(500*(i+1)).fadeIn(300);
        };
    }, 1000);
});

Upvotes: 0

Related Questions