Home > jquery > jQuery doOnce plugin for chaining addicts

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.

Paul Irish jquery

  1. emretemp
    June 21st, 2009 at 14:34 #1

    thx alot. I was looking for smt like this.

For code blocks, use <pre lang="javascript">. css and html4strict are also accepted.

i left this space here for you to play. <3