Paul Irish

Making the www great

jQuery doOnce Plugin for Chaining Addicts

1
2
3
4
5
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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.

Comments