DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Using Event.observe For When A Page Loads

11.20.2006
| 26154 views |
  • submit to reddit
        I just prefer this implementation as opposed to window.onload.

Event.observe( window, 'load', function() {
  // Put the Javascript that needs to happen when the page
  // loads here
} );

For example, here's a way to make most of your input fields and all of your textareas have a different class when they're selected.  Useful if you want to style them differently with CSS.
Event.observe( window, 'load', function() {
  var inputs = document.getElementsByTagName( 'input' );
  var textareas = document.getElementsByTagName( 'textarea' );

  for ( var i=0; i<inputs.length; i++ ) {
    type = inputs[i].type;

    if (
      ( type == 'button' || type == 'reset' ||
      type == 'password' || type == 'text' ||
      type == 'submit' ) &&
      ( inputs[i].onfocus == '' ||
      !inputs[i].onfocus )
    ) {
      inputs[i].onfocus = function() {
        this.className = 'selected';
      }

      inputs[i].onblur = function() {
        this.className = '';
      }
    }
  }

  for ( var i=0; i<textareas.length; i++ ) {
    if ( textareas[i].onfocus == '' || !textareas[i].onfocus ) {
      textareas[i].onclick = function() {
        this.className = 'selected';
      }
      textareas[i].onblur = function() {
        this.className = '';
      }
    }
  }
} );