Javascript Form Highlighting Script — add onBlur and onFocus input styles!

November 26th, 2006 at 1:05 am (web programming, javascript, examples)

Check this out (click in the two input boxes and see what happens):

This unobtrusive javascript snippet (below) will add “highlighting” effects to textareas and text and password input fields. Just define “onBlur” and “onFocus” CSS class styles. The extra bonus (provided exclusively by me <grin/>) is that this function supports multiple class names for the highlighted elements. So your input of class “niftyInput” becomes an input of class “niftyInput onBlur” and, when it’s active, “niftyInput onFocus”.

function addHighlightFunction(field) {
  field.onfocus = function () {
    var N = this.className;
    this.className = N.substring(0, N.length - 7) + ' onFocus';
  }
  field.onblur = function () {
    var N = this.className;
    this.className = N.substring(0, N.length - 8) + ' onBlur';
  }
  field.className = field.className + ' onBlur';
}
function initHighlight() {
  if (!document.getElementsByTagName) { return; }
  var allfields = document.getElementsByTagName('input');
  for (var i=0; i<allfields.length; i++) {
    var field = allfields[i];
    var fieldType = field.getAttribute('type')
    if ((fieldType == 'text') || (fieldType == 'password') ) {
      addHighlightFunction(field);
    }
  }
  var allfields = document.getElementsByTagName("textarea");
  for (var i=0; i<allfields.length; i++){
    var field = allfields[i];
    addHighlightFunction(field);
  }
}
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(initHighlight);

This is adapted from a script by Adam Kalsey, which also uses Simon Willison’s addLoadEvent function.

The effect above is accomplished with this CSS:

.onBlur { border:1px dotted #888; }
.onFocus { border:1px solid #F00; }

Elegant, huh? And if you want these behaviors to be form-specific, try something like this:

#Search .onBlur { border:1px dotted #888; }
#Search .onFocus { border:1px solid #F00; }
#Login .onBlur { border:2px solid #AAA; }
#Login .onFocus { border:2px solid #333; }

1 Comment

  1. Adam Kalsey said,

    November 26, 2006 at 10:25 am

    Excellent! Love the modification.

Close
E-mail It