Over a million developers have joined DZone.

Adding HTML5 placeholder attribute support through progressive enhancement

DZone 's Guide to

Adding HTML5 placeholder attribute support through progressive enhancement

· Web Dev Zone ·
Free Resource

I continually talk about HTML5 and how progressive enhancement is a simple approach to make any new behavior possible in web browsers that haven’t implemented it yet. I thought I’d show you a simple example how to do this with the new placeholder attribute for input elements.

Introducing the placeholder attribute

The placeholder attribute is there to show the user a text, a hint of sorts, but as soon as the text field gets focus, you want that value to be cleared. All the HTML5 code it takes is:

<input type="text" id="search-text" placeholder="Enter terms here">

However, the status of implementation right now is that only WebKit-based web browsers (Google Chrome and Safari) support this. So, what do we do for older web browsers?

For web browsers not supporting the placeholder attribute

There are two things we need to add to get this in web browsers not supporting it:

  • A certain class to display our created placeholder in a semi-disabled fashion
  • A JavaScript snippet to simulate the placeholder attribute behavior


.placeholder {
color: #aaa;



This JavaScript is based on using jQuery for class adding/removing and event handling, but naturally you could use just about any JavaScript library or just write it yourself. Just keeping it short and simple here, ok? :-)

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
// To detect native support for the HTML5 placeholder attribute
var fakeInput = document.createElement("input"),
placeHolderSupport = ("placeholder" in fakeInput);

// Applies placeholder attribute behavior in web browsers that don't support it
if (!placeHolderSupport) {
var searchField = $("#search-text"),
originalText = searchField.attr("placeholder");

searchField.bind("focus", function () {
if (searchField.val() === originalText) {

searchField.bind("blur", function () {
if (searchField.val().length === 0) {


Progressive enhancement

This is an easy example of progressive enhancement: first check for native support, and if it’s not there, implement the same behavior through JavaScript (if JavaScript is available, of course).
Happy scripting!



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}