Little Functions and Classes

I started a thread like this some time ago for the PHP area, but I think this should be a fun topic for js as well. Share your favorite small functions and objects.

This first example requires prototype.js


var EventHandler = Class.create({
	initialize: function() {
		for ( m in this ) {
			if ( m.substring(0,2) == '__' && typeof(this[m]) == 'function' ) {
				this[m.substring(2)] = this[m].bindAsEventListener(this);
			}
		}
	}
});

If you’ve ever created a class that has a lot of listener objects in it this will be useful as a superclass to extend off of as it does the work of binding your event listeners for you. All you have to do is prefix your event handling functions with __. The init function above then parses those functions out into bound listeners.

Any other contributions?

OK, let’s see if it takes off.

Makes a textarea expand automatically to fit the content being typed in, so that no scrollbars appear:

function autogrow() {
  if (!this.clone) {
    this.style.overflow = 'hidden';
    this.clone = document.createElement('textarea');
    this.clone.rows = this.rows;
    this.clone.id = 'clone';
    this.clone.style.visibility = 'hidden';
    this.style.width = this.clone.style.width = this.scrollWidth + 'px';
    this.clone.style.position = 'absolute';
    this.parentNode.insertBefore(this.clone, null);
    this.rows += 1;
  }
  this.clone.value = this.value;
  while (this.clone.scrollWidth < this.scrollWidth) {
    this.rows += 1;
    this.clone.rows += 1;
  }
}

var tarea = document.getElementsByTagName('textarea')[0];

//call it immediately (e.g. onload)
autogrow.call(tarea);

//call it onkeyup
tarea.onkeyup = autogrow;