I have some custom Javascript code that checks for browser support of placeholders and creates them if not supported. This solution works on some older browsers, but not all, especially IE.
The issue I am facing is retrieving the "Placeholder" value; currently in IE9, it returns "undefined".
Below is my current code:
//Check if Placeholders are supported
var test = document.createElement("input");
if ("placeholder" in test) {
var testholder = true;
} else {
var testholder = false;
}
//Fix unsupported Placeholder functionality
function placeHolder(id)
{
var demo = document.getElementById(id);
demo.className = "fix-hint";
demo.value = demo.placeholder;
demo.onfocus = function()
{
if (this.className == "fix-hint")
{
this.value = "";
this.className = "fix-nohint";
}
};
demo.onblur = function()
{
if (this.value === "")
{
this.className = "fix-hint";
this.value = demo.placeholder;
}
};
return false;
}
I prefer using pure Javascript without JQuery as JQuery can be bulky for small tasks, and I want to improve my understanding of Javascript. Although Modernizr is an option for future use, I am not currently utilizing it.
UPDATE
This updated code has been successfully tested in IE 8 and 9. The function call is placed within an if/else condition for "placeSupport".
//Check if placeholders are supported
placeholderSupport = ("placeholder" in document.createElement("input"));
if (!placeholderSupport) {
var placeSupport = false;
} else {
var placeSupport = true;
}
//Add placeholder support for older browsers
function placeHolder(id)
{
var el = document.getElementById(id);
var placeholder = el.getAttribute("placeholder");
el.onfocus = function ()
{
if(this.value == placeholder)
{
this.value = '';
this.className = "fix-nohint";
}
};
el.onblur = function ()
{
if(this.value.length == 0)
{
this.value = placeholder;
this.className = "fix-hint";
}
};
el.onblur();
}
}