jQuery doOnce plugin for chaining addicts
February 28th, 2008
// jQuery doOnce plugin jQuery.fn.doOnce = function(func){ this.length && func.apply(this); return this; }
This allows you to execute arbitrary script during a single chain. A bad example of alert() debugging follows:
// example usage of doOnce() $('div.toGrow') .doOnce(function(){ alert('before color swap'); }) .css({ backgroundColor: 'red'}) .find('h2') .text('And now we\'re red') .end() // go back to the div.toGrow .animate({ height: '+=50px'},'normal','swing',function(){ $(this) // callback when animations complete .find('h2') .text('And now we\'re taller') .doOnce(function(){ alert('animation done'); }); });
Note this is a little different than each(), which will execute once for every element in your current collection.
The code is pretty trivial, but sometimes you just feel like it. Nobody likes to break the chain!
Update 2009.03.04: Length checking added. thx cohitre.
Follow me on twitter: @paul_irish
thx alot. I was looking for smt like this.