Skip to content

Instantly share code, notes, and snippets.

@aarsilv
Created December 9, 2013 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarsilv/7867212 to your computer and use it in GitHub Desktop.
Save aarsilv/7867212 to your computer and use it in GitHub Desktop.
JavaScript file that mimics the functionality of HTML5's placeholder attribute in browsers that don't support it, including Internet Explorer versions older than IE10.
$(function(){
//code from http://stackoverflow.com/questions/8628522/placeholder-not-working-for-internet-explorer
var _debug = false;
var _placeholderSupport = function() {
var t = document.createElement("input");
t.type = "text";
return (typeof t.placeholder !== "undefined");
}();
function HandlePlaceholder(oTextbox) {
if (!_placeholderSupport) {
var curPlaceholder = oTextbox.getAttribute("placeholder");
if (curPlaceholder && curPlaceholder.length > 0) {
Debug("Placeholder found for input box '" + oTextbox.name + "': " + curPlaceholder);
oTextbox.value = curPlaceholder;
oTextbox.setAttribute("old_color", oTextbox.style.color);
oTextbox.style.color = "#c0c0c0";
oTextbox.onfocus = function() {
Debug("input box '" + this.name + "' focus");
this.style.color = this.getAttribute("old_color");
if (this.value === curPlaceholder)
this.value = "";
};
oTextbox.onblur = function() {
Debug("input box '" + this.name + "' blur");
if (this.value === "") {
this.style.color = "#c0c0c0";
this.value = curPlaceholder;
}
};
}
else {
Debug("input box '" + oTextbox.name + "' does not have placeholder attribute");
}
}
else {
Debug("browser has native support for placeholder");
}
}
function Debug(msg) {
if (typeof _debug !== "undefined" && _debug) {
var oConsole = document.getElementById("Console");
if (!oConsole) {
oConsole = document.createElement("div");
oConsole.id = "Console";
document.body.appendChild(oConsole);
}
oConsole.innerHTML += msg + "<br />";
}
}
// below code added by Aaron Silverman; depends on jQuery being loaded.
function handlePassword($input) {
var $password = $input.clone().attr('type','text');
$input.after($password);
$input.hide();
$password.on('focus', function(ev) {
$password.remove();
$input.show();
$input.focus();
});
HandlePlaceholder($password.get(0));
}
$('input').each(function(i, el) {
var $input = $(el);
var type = $input.attr('type');
if (!type || type === 'text') {
HandlePlaceholder(el);
} else if (type === 'password') {
handlePassword($input);
$input.on('change', function(ev) {
if (!$input.val()) {
handlePassword($input);
}
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment