Default Text Field Value without Javascript (placeholder)

Posted on

A reader commented on one of my other posts about a JavaScript method that may be less taxing on the users browser. He pointed out how my js script for hiding form input values on focus could be improved.

Turns out there is a handy little method: textObject.defaultValue. Instead of using the .val() method, it would be slightly better to use the one he mentioned.

However, I have another way, which I hope most of you know about already, but I will put it out there just to make sure. Its an HTML5 attribute called placeholder.

It looks like this:

<input type="text" placeholder="Your Placeholder Text" />

Which renders like:

Go ahead and click in the text field and click out of it. The placeholder does what JavaScript use to do!

There is even a way to style the placeholder text with css… like so:

::-webkit-input-placeholder {
   color: #ccc;

:-moz-placeholder {
   color: #ccc;

Long Story Short

Don’t use JavaScript where you can do the same thing with HTML or CSS! However, my script with the updated methods would be a good fallback for browsers that do not support placeholder text. Also, big thanks to Karl Ringrose for pointing out the js method!

Thanks and Happy Coding!