HTML5 Placeholder Enabler

In this post I will continue the series dedicated to HTML5 and enabling certain features of the language for browsers that still do not support them.

This tutorial also assumes the YUI JavaScript library and its code is in the same namespace as the HTML5 Details Element Enabler I wrote about last week.

According to WhatWG, “The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.“.  As of October 2011 it is not yet supported by Internet Explorer.

The solution presented in this post checks for the availability of the placeholder attribute in textboxes, and if it is not available applies its content as value to the elements that contain it. In order to achieve similar appearance as the real placeholder element we will also add or respectively remove a special CSS class name:

In short, the feature detection is:

var textarea = document.createElement("textarea");

if(undefined === textarea.placeholder) {
// execute code only for browsers that do not support placeholder
}

The _bind() method is pretty straightforward – we assign handlers for the focus() and blur() events, and according to the value of the input we set or unset the placeholder text:

_enable = function(e) {

var
element = e.currentTarget,
type = e.type;

switch(type){
case "focus":
if(element.get("value") === element.getAttribute("placeholder")) {
_set(element, false);
}
break;
case "blur":
if(element.get("value") === "") {
_set(element, true);
}
break;
}
}

The Markup:

<input type="text" placeholder="my placeholder text" />
<textarea placeholder="my placeholder text"></textarea>
<input type="password" placeholder="my placeholder text" />

The CSS Emulating the System Placeholder Style:

.placeholder-enabler
{
color: #ccc;
}

The demo is available on this page. If you are curious about more HTML5, CSS3 and JavaScript experiments, bookmark this page.

Related Posts

14 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>