HTML5 Tutorial - Input Attr : Placeholder

Input Attr : Placeholder

A placeholder is a textbox that hold a text in lighter shade when there is no value and not focused.

Below is how a placeholder should look like if no value is entered and textbox is not focus. (What you see is just picture, not real placeholder, don't try to click it)

placeholder without value

Once the textbox gets focus, the text goes off and you shall input your own text.

placeholder without value

Without going further, let's have a simple demo

:

..and, here is the code. Javascript and CSS is no longer needed to handle the appearance of the text.

<label for="first_name">First Name</label> : <input id="first_name" placeholder="First name goes here">

Let's see what which browsers support placeholder.

BrowsersPlaceholder Support
IE 10
Firefox 3.7
Safari 4.0
Chrome 4.0
Opera 11

If placeholder is just a nice-to-have feature in your web page, you probably will not bother about supporting browsers other than above.

Otherwise, you would have to go extra mile. First, use Javascript to check if the browser support Placeholder, for browsers that does not support Placeholder, use Javascript + CSS to create a Placeholder on your own.

<label for="demo">Placeholder demo</label> : <input id ="demo" placeholder="Support Placeholder" />

<script>
function testAttribute(element, attribute)
{
  var test = document.createElement(element);
  if (attribute in test)
    return true;
  else
    return false;
}

if (!testAttribute("input", "placeholder"))
{
  window.onload = function()
  {
    var demo = document.getElementById("demo");
    var text_content = "No Placeholder support";

    demo.style.color = "gray";
    demo.value = text_content;

    demo.onfocus = function() {
    if (this.style.color == "gray")
    { this.value = ""; this.style.color = "black" }
    }

    demo.onblur = function() {
    if (this.value == "")
    { this.style.color = "gray"; this.value = text_content; }
    }
  }
}
</script>

"testAttribute" function above is to test if an attribute of an element is supported by a web browser. In this case, we want to know if your web browser supports "Placeholder" attribute of "Input" element.

If "Placeholder is not supported, I make the browser to run some Javascript code to do create something as a Placeholder, you can use your own Javascript instead of mine, (my code is created for showcase and might not be suitable for production)

:

If you are using a web browser that supports "Placeholder", you should be able to see "Support Placeholder" in the textbox. Conversely, you will see "No Placeholder Support" if you are using web browser such as Internet Explorer 8.