Creating some javascript that can mimic the HTML5 behavior of a placeholder= attribute on an input element can be simple. Unfortunately, getting a single solution you can work with that fits all browsers and have little overhead to work with is not that easy.
The following are the requirements when making it universal:
- work as progressive enhancement for browsers that don’t support it only (feature-detect)
- respect initial values
- be able to attach and detach the placeholder behavior on demand
Since the progressive enhancement only works by using the value property of the input in older browsers, it presents a problem for form validation. You don’t want your form submission to go through with fields that have the placeholders assigned as the actual values. This is not what the native placeholder behavior is so you need a way to remove the enhancement prior to your form validation and submission. You also need to be able to re-attach it, should validation fail and submission be stopped pending user action.
http://jsfiddle.net/dimitar/bYQ8P/ is the updated mooPlaceholder class. I suggest you view it in IE6/7/8 to actually experience the difference. It should act *exactly* how the placeholder works in say, FireFox 7. To get around the jsfiddle issues with IE, view it under the full /show/ url here
So, to recap: if you want to validate a form that has child elements managed by the class, you’d do the following when using my Class:
var placeholders = new mooPlaceholder().attachToElements(); // add it. formElement.addEvent("submit", function(e) { // remove placeholder while validating... placeholders.detachFromElements(); // run validation code here. if (failed) { e.stop(); // stop submit placeholders.attachToElements(); // restore placeholders } });
I think this overhead is quite acceptable, considering. It can be done automatically on your form submits by doing a element.getParent(“form”) but this way is also fine. Hope it helps somebody.
GitHub flavoured markdown enabled.