Unobtrusive suggested input text with jQuery

You can do this with any framework, of course, but I've just implemented a subtle piece of jQuery-supported code in my blog search to make the suggested text disappear when you focus into it, and re-fill an empty field with the suggested text when you move focus away from the box by clicking elsewhere. Give it a try in the input field up there (here if you're reading this over a syndication).

jQuery is especially good for writing document-driven code, as its functional programming style means that you're less likely to reach an error condition if the HTML you're trying to hook up to simply stops existing: if there's a page without that search box, for example, then the code simply reaches the point of an empty node set and then quietly stops. It's like at every stage you have a foreach loop over the most recent set of elements that jQuery has found for you, so that a non-existent element results in an empty loop, not an error. Of course, you can still shoot yourself in the foot if one of two interdependent pieces of a document is missing, and your Javascript does something plain screwy in its absence. No framework can protect you from total page meltdown.

The code below is basically what I've used, along with two input elements: the visible one (ID="s") and an invisible hidden one (ID="s_orig") containing the replacement text that pops back into the box when it's left empty. The Javascript is saved as base.js, although that particular file might change over time as I add extra behaviour.

Client = {
  // focus function
  inputFocus: function() {
    if ( this.value == jQuery("#s_orig").get(0).value ) {
      this.value = "";
    }
  },

  // blur function
  inputBlur: function() {
    if (this.value == "") {
      this.value = jQuery("#s_orig").get(0).value;
    }
  },

  go: function() {
    // tie the two functions to the Javascript
    jQuery("#s").focus(Client.inputFocus
      ).blur(Client.inputBlur
      // Run the blur function to put the text there
      ).blur();
  }
};

// Run the Keyword.go() function when the page is ready
jQuery(document).ready(Client.go);

This was based on a post to the development mailing list on drupal.org. I've tidied it up a bit, and removed a couple of bugs.