Skip to content

Instantly share code, notes, and snippets.

@dwarfmondo
Created May 1, 2011 19:12
Show Gist options
  • Save dwarfmondo/950756 to your computer and use it in GitHub Desktop.
Save dwarfmondo/950756 to your computer and use it in GitHub Desktop.
Add placeholder text functionality for IE.
/*
CSS to style the placeholder text.
Separate rule for Firefox.
Cannot stack with WebKit's.
*/
input.placeholder_text,
textarea.placeholder_text {
color: #777;
}
::-webkit-input-placeholder {
color: #777;
}
// This assumes you're using jQuery. This does the heavy lifting.
function setPlaceholderText() {
var PLACEHOLDER_SUPPORTED = 'placeholder' in document.createElement('input');
if (PLACEHOLDER_SUPPORTED || !$(':input[placeholder]').length) {
return;
}
$(':input[placeholder]').each(function() {
var el = $(this);
var text = el.attr('placeholder');
function add_placeholder() {
if (!el.val() || el.val() === text) {
el.val(text).addClass('placeholder_text');
}
}
add_placeholder();
el.focus(function() {
if (el.val() === text) {
el.val('').removeClass('placeholder_text');;
}
}).blur(function() {
if (!el.val()) {
el.val(text).addClass('placeholder_text');;
}
});
el.closest('form').submit(function() {
if (el.val() === text) {
el.val('');
}
}).bind('reset', function() {
setTimeout(add_placeholder, 50);
});
});
}
// Include this at the bottom of your html file.
$(document).ready(function(){
setPlaceholderText();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment