06 March 2013

Support the HTML5 placeholder Attribute in Browsers that do not support it


HTML5 language gives us the possibility of a Placeholder.
The placeholder Attribute gives us information on the textbox where we are supposed to use.

All you need is to add the same type of input tag.


<input type="text" name="first_name" placeholder="First name">


Browsers that do not support it will show like:



Browsers that support it will show like:



If you want the older browsers will support it, all you have to do is add the following JQuery code:



/* Input Tag Placeholder Support*/
function IsInputPlaceholderSupport() {
    var i = document.createElement('input');
    return 'placeholder' in i;
}
$(document).ready(function () {
    if (!IsInputPlaceholderSupport()) {
        var fields = $('input');
        for (var i = 0; i < fields.length; i++) {
            if (fields[i].attributes['placeholder'] != undefined) {
                fields[i].defaultValue = fields[i].attributes['placeholder'].value;
                fields[i].value = fields[i].attributes['placeholder'].value;
                fields[i].onfocus = function () { if (this.value == this.defaultValue) this.value = ''; };
                fields[i].onblur = function () { if (this.value == '') this.value = this.defaultValue; };
            }
        }
    }
});
/* End Input Tag Placeholder Support*/


Yours,
Roi