Placeholders using Javascript
Posted by Mark Fenoglio under CSS, Javascript for developerBlog
October 9, 2009
Search element with placeholder text
Search element with placeholder text

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/search.js"></script>
<link rel="stylesheet" type="text/css" href="lib/public.css" />
</head>
<body onload="javascript:set_search_placeholder();">

<form name="blog_search" method="post" action="search.php">
<input name="_search" type="text" id="search_dblog" class="default_value" 
       onfocus="javascript:remove_search_placeholder();" 
       onblur="javascript:set_search_placeholder();" />
<a href="javascript:submit_search();" class="search_go">Find</a>
</form>
</body>
</html>

Javascript

To make our placeholder work, we need two javascript functions, set_search_placeholder() and remove_search_placeholder(). Rather than use an ordinary submit button, we'll use stylesheets to make it look pretty and a javascript function to make it go.

Listing: lib/search.js
function set_search_placeholder() {
    searchNodes = document.getElementsByName('_search');
    searchField = searchNodes[0];
    if (! searchField.value) {
        searchField.value = "Search developerBlog";
        searchField.style.color = '#999';
    }
}

function remove_search_placeholder() {
    searchNodes = document.getElementsByName('_search');
    searchField = searchNodes[0];
    if (searchField.value=="Search developerBlog") {
        searchField.value = '';
        searchField.style.color = '#000';
    }
}

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

CSS

We just need a bit of style to make the "Find" button look the way we'd like (for brevity sake, I haven't included the entire stylesheet).

Partial Listing: lib/public.css
a.search_go {
    border: 1px solid #333;
    margin: 0 0 0 2px;
    padding: 1px 3px 1px 2px;
    background-color: #999;
    color: #fff;
    text-decoration: none;
    font-family: Optima, arial, sans-serif;
    font-size: 11px;
}