del.icio.us .:. tweet

Input Placeholders for Everyone .:. kentbrewster.com

In my travels for Vurve, and last year while at Netflix, I'm running into the new placeholder attribute for INPUT tags. Placeholders are sweet; they supply the reader with a hint about what he's supposed to enter in a text field, allowing for much tighter design. Code for placeholders looks something like this:

<input type="text" placeholder="username" />
<input type="text" placeholder="e-mail" />
<input type="password" placeholder="password1" />
<input type="password" placeholder="password2" />

Sadly, placeholders only work with the most recent browsers, which do NOT include Firefox less than version 4 or IE less than version 9.

Here's a standalone script that:

  • Checks if we're using a browser that doesn't recognize placeholders.
  • Looks for text or password fields that have placeholders.
  • Creates absolutely-positioned SPAN tags, sets their innerHTML to whatever's in the placeholder, and inserts them immediately before their INPUT tags.
  • Hides or shows them at the right times, depending on whether the field already has a value, and on events like focus, blur, and mousedown.

Hasn't This Already Been Handled?

Yes. Dave Sparks did it over on kamikazimusic.com with jQuery and Modernizr and Dave Dorward posted a non-library-based solution on stackoverflow in August of 2010. I wrote this 1) for fun, 2) because I tend not to require libraries unless I absolutely, positively must, and 3) because I don't like solutions that mess around with the VALUE attribute or add a LABEL to the DOM.

Try It Here:

(has a prefilled value; delete to see the placeholder)

The Script

Notes

  • I've taken steps to move placeholder styling to the last line of the script; feel free to tweak the font size or color if it's not quite right.
  • If you want to use a different global namespace than IP, go right ahead. It only appears once, on that very last line.
  • When you're creating new INPUT boxes on the fly, you should be able to do this:

    IP.f.makePlaceHolder(yourInput, yourPlaceholder);

    ... any time after page load.

  • Yes, I'm seeing the delay between page load and placeholders appearing; this is because of my other third-party scripts (Disqus, Delicious, Twitter, and Delicious) which are taking a while. As long as it's being called after your last INPUT tag, it's probably safe to fire it off immediately instead of waiting for page load; to do that, you'd remove this line:

    $.f.listen($.w, 'load', $.f.init);

    ... and substitute this:

    $.f.init();

If it looks like it will be useful, feel free to fork Input Placeholders For Everyone on GitHub. As always, have fun, and please let me know how it works.

Copyright Kent Brewster 1987-2014 .:. FAQ .:. RSS .:. Contact