Last Updated: February 25, 2016
·
3.532K
· magalhini

jQuery shift() implementation

I often like to iterate over a jQuery collection the same way I iterate over a normal array with the native shift() method, but you can't call shift() on a jQuery collection. You'd have to push() each element into a new array, which sort of sucks.

Luckily you can very easily implement your own shift() equivalent:

$.fn.shift = function () {
    var x = this.eq(0);
    this.splice(0,1);
    return x;
}

So if you wanted to fade out the elements of a jQuery object, one at a time, you could use shift() to manipulate the original object:

var obj = $('.items');

(function walk(o) {
    $(o).fadeOut(500, function () {
        if (obj.length) {
            walk(obj.shift()); //<<< here's our baby!
        }
    });
}(obj.shift()));

1 Response
Add your response

Very nice function!

I might have to implement this into my current piece of work. Thanks!

over 1 year ago ·