Javascript Field Placeholders

One standard feature on most blogs (and lots of other places, of course) is a search widget. I wanted to make sure that its functionality was obvious without having to resort to a label sitting on top of it (or next to it). So, I experimented with a little Javascript to create some placeholder text to make clear what purpose the field served. Once the user clicks in the field, I also want the placeholder text to go away (and then return when the user leaves the field if it is empty).

HTML

The simple search text field, of course, needs to be wrapped in a form, and in order for the effects to take place that we want, we need to do some things when the page loads.

Listing: index.html

<html>
<head>
<script src="lib/js/search.js"></script>
<link rel="stylesheet" type="text/css" href="lib/public.css" />
</head>
<body>

<form id="blog_search" name="blog_search" method="get" action="/iw/blog">
<input id="search_input" name="s" type="text" size="25" maxlength="40"
       onfocus="javascript:remove_placeholder(this);"
       onkeyup="javascript:use_typing_color(this);"
        onblur="javascript:set_placeholder(this);" />
<a href="javascript:submit_search();" class="search_go">
   <img src="/iw/img/icon/go-gray.png" alt="Do Search" />
</a>
</form>

<script type="text/javascript">
bring_focus_to_search();
</script>

</body>
</html>

Javascript

To make our placeholder work, we need two javascript functions, set_placeholder() and remove_placeholder(). Rather than use an ordinary submit button, we'll use graphics and style sheets to make it look spiffy, and a javascript function to make it work.

Listing: lib/js/search.js

function bring_focus_to_search() {
   document.blog_search.s.focus();
   set_placeholder(document.blog_search.s);
   document.blog_search.s.select();
}

function set_placeholder(field) {
   if (field.value) return;

   field.value = 'Search the Developer Blog';
   field.style.color = '#999';
}

function remove_placeholder(field) {
   if (field.value != 'Search the Developer Blog') return;

   field.value = '';
   field.style.color = '#333';
}

function use_typing_color(field) {
   field.style.color = '#333';
}

function submit_search() {
   document.blog_search.submit();
}

Cascading Syle Sheets (CSS)

A couple simple styles help the input field and search button line up properly.

Partial Listing: lib/css/blog.css

#search input {
   margin-top: 10px;
   display: block;
   float: left;
}