Last Updated: February 25, 2016
·
3.809K
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside