Update: I have created a better version of this script that, among other improvements, supports password fields, unlike the code below.
Placeholder is a very useful attribute of the <input> tag that is specified in the HTML5 spec. It provides a text that goes into the field, by default, and is used as a kind of a quick tip for the user about what they should type into the field, such as “type to search”, or “type in username”. The nice thing about “placeholder”, as oppose to, for example, simply setting some value for the field, is that it automatically disappears when the user starts typing something in, but it reappears if the user ends up leaving the field empty. Unfortunately this attribute, and its functionality, is actually not supported by most browsers, including Firefox 3.6 and IE8, it is however supported by Chrome 4, and possibly Safari 4 though I can’t vouch for the latter.
I recently had a few projects that needed this functionality, and while some of them had email, password and other fields that required validation, one needed just very simple text fields with placeholder text. So I wrote this very simple javascript function, using jQuery, to do just that (I’m using jQuery 1.4.2 here).
function setupPlaceholder(inputid) {
if ($.browser.webkit) return false;
var target = $('#'+inputid);
if (target.length==0) {
target = $('input[type="text"], input[type="email"], input[type="search"]');
}
target.each( function(i, el) {
el = $(el);
var ph = el.attr('placeholder');
if (!ph) return true;
el.addClass('placeholder');
el.attr('value', ph);
el.focus( function(e) {
if( el.val()==ph ) {
el.removeClass('placeholder');
el.attr('value', '');
}
});
el.blur( function(e) {
if( $.trim(el.val())=='' ) {
el.addClass('placeholder');
el.attr('value', ph);
}
});
});
}
The code is very straightforward. For one it checks that this is not a webkit browser, if it is I assume it supports placeholder attribute and so doesn’t need the code. Then it checks if an ID for the input was provided, just in case I wanted to do this on one field only. If there is no ID, or if it wasn’t found, it’ll simply apply to all inputs of type text, email or search (HTML5 input types).
When combined with some styles you end up with a nice input field with some “help” text, like this.
The one “catch” with this script is that I don’t check the case where a user would put the same text in as the placeholder text. If the user does this, then when they focus on the field again, the text will be erased (’cause the script thought it’s the placeholder text). To fix that you can add a flag that keeps track of whether the user has edited the field or not.
[…] Mark Pilgrim’s Dive into HTML5 covers every base in complete detail. [↩]Thanks to Ilia Draznin […]
[…] while back I made a post about a simple placeholder script I wrote. The idea was to provide the placeholder functionality that browsers like Chrome and […]