Sunday, April 18, 2010

Prototype JS - Auto-Resize Text Area

Recently needed to auto-resize or auto-grow a text area in a form (with a maximum size).  Below is short a little Prototype JS version which you invoke by using:





new TextAreaResize('idOfElement');



This utility does not resize the text area smaller if an user deletes data from the text area (which is expected in most cases).





var TextAreaResize = Class.create();

TextAreaResize.prototype = {

    /*
     * PROPERTIES
    */
   
    /*
     *
     * OPTIONS:
     * maxRows: integer (default 50)
     * The maximum number of rows to grow the text area
     *
    */
   
   
    /*
    * INITIALIZATION - CONFIGURATION
    */
    initialize: function(element, options) {
        this.element = $(element);       
        this.options = Object.extend({maxRows: 50}, options || {} );

        Event.observe(this.element, 'keyup', this.onKeyUp.bindAsEventListener(this));
        this.onKeyUp();
    },

    /*
    * PUBLIC FUNTIONS
    */   
    onKeyUp: function() {       
        while (this.element.scrollHeight > this.element.offsetHeight && this.element.rows < this.options.maxRows) {
            if (this.element.rows < this.options.maxRows) {
                this.element.rows = this.element.rows + 1;
            }
        }
    }
};


No comments:

Post a Comment