Smart technique to make placeholder to work in all the browsers

The placeholder attribute specifies a short hint that describes the expected value of an input field, the short hint is displayed in the input field before the user enters a value. The placeholder attribute is supported in Internet Explorer 10, Firefox, Opera, Chrome, and Safari. Its a pain for developers to make it work for browsers which doesn’t support placeholder. We do have lots of plugins, which will enable us to fix this issue, however most of them are complicated solutions.

Well, I have a simple solution to make it work for browsers which does not support placeholder.

1. Please add the latest jquery reference to the page  [I have used jquery.1.11.1 ]

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2. Design the page with placeholder attribute


<input type="text" name="firstName" placeholder="First name">
eg: 

3. Just add the magic script to the page.


$.support.placeholder = ('placeholder' in document.createElement('input'));
if (!$.support.placeholder) {
      $('[placeholder]').each(function () {
            if ($(this).val() === "") {
                  $(this).val($(this).attr("placeholder"));
                  $(this).addClass("placeholderstyle");
            }
      });
      $("[placeholder]").focus(function() {
            if ($(this).val() === $(this).attr("placeholder")) {
                  $(this).val("");
                  $(this).removeClass("placeholderstyle");
            }
      }).blur(function() {
            if ($(this).val() === "") {
                  $(this).val($(this).attr("placeholder"));
                  $(this).addClass("placeholderstyle");
            }
      });
}

Basically we are checking the browser supports place holder attribute or not. If it returns false, we inject our piece of code. On load we move the place holder data to value attribute, so when the page loads place holders are already in place. Two basic placeholder events are blur and focus, on focus we remove the value and on blur we put the value back. To look like placeholder we can add simple css styling, in this case I use ‘placeholderstyle’ with color #B1A9B1.

Simple Solution … 🙂