twitter facebook dribbble email

Non-HTML5 placeholder text

Careful! This post is looking a little old and could be inaccurate in many, many ways

After reading about HTML5 for what seems like months I finally got my hands dirty and started playing with the new shiny on a production website. Although I can see the power of HTML5 I think the level of browsers support in some areas means that little more than the basics such as the new tags can be used to any great effect.

One such feature that I did use however was the placeholder attribute, but unfortunately this isn’t yet supported in Firefox which is my yard stick as to whether anything is truly worth using in client websites.

What is the placeholder attribute?

For those yet to read up on HTML5 the placeholder attribute is something that is used with form fields such as a textbox to insert content into a input that acts as a hint as to the purpose of the input. This text then disappears when the user wishes to enter or has entered anything into the input. The code for this nifty trick is this:

But it’s not quite ready yet

Like I said it’s not yet supported in all the browsers, even if you exclude the various IE’s from that statement. So for now if you feel a cross browser solution is a requirement an alternative solution is needed, maybe something like this:

This is the code I use, over the past few years it’s undergone a few changes and I may yet find a way to reduce the code even more, but for now it does the job. Those who have read the code will also realise that this code won’t simply work alone. In addition to this you will need to add a title attribute to any input fields you wish to display any placeholder text.

What is great about this code is that if the title doesn’t exist then the code simply does nothing, unfortunately I can’t say that about this next bit…

Combining the two

It’s possible to combine both of these with a couple of changes to the code and the addition of Modernizr. This way you get to implement the cool new thing as well as provide a fallback for those using older browsers, even IE6. The altered code looks like this:

Of course I did say there’s an issue here. I’ve actually only started to use this myself and have noticed that in the absence of the placeholder attribute the JavaScript code will return ‘undefined’ into the input box. Therefore if you expect to have any input boxes that won’t be using the placeholder attribute you will need to alter the JavaScript code in order to test for this.