SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    I solve practical problems. bronze trophy
    Michael Morris's Avatar
    Join Date
    Jan 2008
    Location
    Knoxville TN
    Posts
    2,011
    Mentioned
    57 Post(s)
    Tagged
    0 Thread(s)

    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
    Code:
    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?

  2. #2
    I meant that to happen silver trophybronze trophy Raffles's Avatar
    Join Date
    Sep 2005
    Location
    Tanzania
    Posts
    4,662
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    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:

    Code javascript:
    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;


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •