Skip to content

Instantly share code, notes, and snippets.

@keif
Created December 20, 2012 20:00
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 keif/4348098 to your computer and use it in GitHub Desktop.
Save keif/4348098 to your computer and use it in GitHub Desktop.
This mimics the HTML5 placeholder in browsers that don't support it. Requires jQuery - can be changed for earlier versions by converting the .on() event calls. The "blur" class was used to apply a lighter gray color to the text.
var placeholderSupport = ("placeholder" in document.createElement("input"));
var setPlaceHolderText = function(elem) {
var $textarea = $(elem);
var placeholderText = $textarea.attr("placeholder");
$textarea.data("placeholder", placeholderText);
if (placeholderText.length > 0) {
$textarea.val(placeholderText)
.addClass('blur');
}
};
var getKey = function(e) {
if (e.keyCode) {
return e.keyCode;
} else if (e.which) {
return e.which;
}
};
var isAlphanumeric = function(e) {
var key = getKey(e);
return (/^[a-z0-9 ]/gi).test(String.fromCharCode(key));
};
var positionCaret = function(elem, pos) {
var range = elem.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
};
// onload comment areas
$('textarea').each(function(i, el) {
if (!placeholderSupport) {
setPlaceHolderText(this);
}
});
// textarea events
$('textarea').on('click focus input change keydown keyup', function(e) {
var $textarea = $(this);
if (!placeholderSupport) {
var placeholderText = base.$commentarea.data("placeholder");
if (this.value === placeholderText) {
positionCaret(this, 0);
} else if (this.value === "") {
this.value = placeholderText;
$textarea.addClass('blur');
}
if (isAlphanumeric(e)) {
if (this.value === placeholderText) {
this.value = "";
}
$textarea.removeClass('blur');
}
}
// handle IE ignoring maxlength
var str = $(this).val();
var mx = parseInt($(this).attr('maxlength'), 10);
if (str.length > mx) {
$(this).val(str.substr(0, mx));
return false;
}
}).on('blur', function(e) {
var $textarea = $(this);
if (!placeholderSupport) {
$textarea.val($textarea.data("placeholder"));
$textarea.addClass('blur');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment