Example D

A Slightly Better-Behaved Dynamic Labels Script

This page demonstrates an implementation of the dynamic label script that improves upon the one in Example C.

We've added code to prevent it from submitting the label text to the server if the form is submitted with no text in the dynamic label fields. It still doesn't degrade properly, however.

It still uses the same HTML and CSS:

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

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

But we've changed the 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;
        }
      }

      for (var i = 0; i < document.forms.length; i++) {
        addEvent(document.forms[i], "submit", resetLabels);
      }
    }

    function resetLabels(event) {
      var elm = getEventSrc(event);
      var objLabels = elm.getElementsByTagName("LABEL");
      var objField;

      for (var i = 0; i < objLabels.length; i++) {
        if ("dynamicLabel" == objLabels[i].className) {
          objField = document.getElementById(objLabels[i].htmlFor);
          if (objField._labelText == objField.value) {
            objField.value = "";
          }
        }
      }
    }

    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.originalTarget)
        return e.originalTarget;
      else if (e.srcElement)
        return e.srcElement;
    }
  </script>