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()));
Written by Ricardo Magalhães
Related protips
1 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
Best
#Jquery
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#