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:
[sourcecode language=”javascript”]
var textarea = document.createElement("textarea");
if(undefined === textarea.placeholder) {
// execute code only for browsers that do not support placeholder
}
[/sourcecode]
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:
[sourcecode language=”javascript”]
_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;
}
}
[/sourcecode]
The Markup:
[sourcecode language=”html”]
<input type="text" placeholder="my placeholder text" />
<textarea placeholder="my placeholder text"></textarea>
<input type="password" placeholder="my placeholder text" />
[/sourcecode]
The CSS Emulating the System Placeholder Style:
[sourcecode language=”css”].placeholder-enabler
{
color: #ccc;
}[/sourcecode]
The demo is available on this page. If you are curious about more HTML5, CSS3 and JavaScript experiments, bookmark this page.
Related Posts
© 2006 - 2023 Martin Ivanov