Created
December 20, 2012 20:00
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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