Use the placeholder attribute. Of course, that doesn't work in IE, and there are many solutions out there to overcome IE's lack of support. Most of these are not very good, especially those that change the value of the input element to accomplish the placeholder text. This approach is buggy and has accessibility issues.
The better approach is to use a technique that doesn't modify the input's value. It should work automatically with forms that already use the placeholder
attribute with no additional changes to the markup. The technique I use is to place a label behind the input so that it shows through the input. When the input has focus or a value, it gets a background color to hide the placeholder label.
First I check to see if the browser natively supports placeholder
. This code tells us whether placeholder is supported:
if (!("placeholder" in document.createElement("input"))) {
// placeholder is not natively supported
}
If placeholder
is not supported, I inject an absolutely positioned <label>
before each <input>
that has a placeholder
attribute and I add a noplaceholder
class to the input indicating that placeholder is not natively supported and that the label should show through the input. I use CSS to style the label to match the input and decrease the opacity of the input so that the label shows through. The rest is just pretty straightforward event handling to add or remove the noplaceholder
class depending on whether the input has focus and/or a value.
Here's my code. Drop the following CSS and JavaScript into an existing page that uses placeholder attributes and it should work. The CSS may require a little tweaking to get it to work on your page.
Demo: http://jsfiddle.net/yjfvm/2/
The CSS:
input[placeholder], .placeholder {
font-family: Sans-Serif;
border: 1px solid #b2b2b2;
border-radius: 3px;
padding: 2px 4px;
vertical-align: middle;
font-size: 1em;
line-height: 1em;
}
.placeholder + input[placeholder].noplaceholder {
filter: alpha(opacity=100);
background-color: #fff;
border-color: #b2b2b2;
}
.placeholder + input[placeholder] {
position: relative;
filter: alpha(opacity=50);
border-color: #666;
}
.placeholder, label.placeholder {
border-color: #fff;
position: absolute;
margin-top: 1px;
margin-left: 0;
top: auto;
}
The JavaScript:
if (!("placeholder" in document.createElement("input"))) {
$(function() {
$("input[placeholder]").each(function() {
$("<label>")
.attr("for", this.id)
.addClass("placeholder")
.text(this.getAttribute("placeholder"))
.insertBefore(this);
$(this).addClass("noplaceholder");
}).on("keydown focus input", function() {
$(this).addClass("noplaceholder");
}).on("change blur", function() {
if (!this.value) {
$(this).removeClass("noplaceholder");
}
}).change();
$("form").on("reset", function() {
setTimeout(function() {
$("input[placeholder]:not(:focus)").change();
}, 0);
});
});
}