scriptNode

Web development with a focus on JavaScript RSS

Dynamic Input

Novice Matt Hackett Published June 15th, 2008 by Matt Hackett

Welcome to the first Script Sunday! Each Sunday, I'll be posting a script to the site. Some will be useful, some will be (hopefully) interesting, and some will be just for fun.

This week I've provided a very simple script that I've used countless times. See the search form in the sidebar? The default text should be "Search for…", but when you focus on the input, the text goes away (and sometimes the style changes), allowing you to search without having to delete any text first. This is very common, unobtrusive behavior that's used so much because it's convenient and intuitive. Now you can use it too! Here's the code:

You may notice that this script attaches to the events directly, which will override any previously set events using the same method (not recommended). The reason I did it this way is to remove any dependency on a JavaScript library. You could alter the code very easily to use whatever library you fancy. For instance, if you're a YUI fan, instead of el.onblur = function(){}, try YAHOO.util.Event.addListener(el, 'blur', function(){});.

There's only one argument (an object) to pass into dynamicInput. The keys for this object are as follows:

  • id - The id of the input element
  • text - The default text to use (for example, "Search Now!")
  • classFocus - The CSS class to set on the input when the focus event is fired (optional)
  • classBlur - The CSS class to set on the input when the blur event is fired (optional)

And here's a quick example of how to use this script:

It's as easy as that! Enjoy!

Read other articles tagged: , , ,

Thoughts?

(required)

© 2009 scriptNode