Example C

A Pretty Well-Behaved Dynamic Label Script

This page demonstrates an implementation of the dynamic label script that is pretty well-behaved.

It is well-modularized and doesn't exclusively use event handlers. However, it still couples to the code that processes the form and it does not degrade properly when JavaScript is not available.

It still uses almost the same basic HTML structure:

  <form>
    <label for="username" class="dynamicLabel">Username</label>
    <input type="text" id="username" name="username" />
  </form>

But we've added this CSS:

  <style type="text/css">
    label {
      display:none;
      }
  </style>

...and this JavaScript:

  <script type="text/javascript">
    addEvent(window, "load", setupLabels);

    function setupLabels() {
      var objLabels = document.getElementsByTagName("LABEL");
      var objField;

      for (var i = 0; i < objLabels.length; i++) {
        if ("dynamicLabel" == objLabels[i].className) {
          objField = document.getElementById(objLabels[i].htmlFor);
          addEvent(objField, "focus", focusDynamicLabel);
          addEvent(objField, "blur", blurDynamicLabel);
          objField._labelText = objLabels[i].firstChild.nodeValue;
          objField.value = objField._labelText;
        }
      }
    }

    function addEvent(objObject, strEventName, fnHandler) {
      if (objObject.addEventListener)
        objObject.addEventListener(strEventName, fnHandler, false);
      else if (objObject.attachEvent)
        objObject.attachEvent("on" + strEventName, fnHandler);
    }

    function focusDynamicLabel(event) {
      var elm = getEventSrc(event);
      if (elm._labelText == elm.value) {
        elm.value = "";
      }
    }

    function blurDynamicLabel(event) {
      var elm = getEventSrc(event);
      if ("" == elm.value) {
        elm.value = elm._labelText;
      }
    }

    function getEventSrc(e) {
      if (!e) e = window.event;

      if (e.target)
        return e.target;
      else if (e.srcElement)
        return e.srcElement;
    }
  </script>