PlaceholderInput
PlaceholderInput is a class that enables inputs to have placeholder values.
Introduction
Placeholders for text inputs are common in the web nowadays. The advantage of this implementation is that it modifies the value accessor property of MooTools, so that when the input value is retrieved from a script and the placeholder is set, an empty string will be returned instead.
This means that if you have initialized PlaceholderInput instances within a form, and then you send it through a remote Request, the placeholders won’t be sent.
Explanation
This article from my blog explains alternative approaches, and why this particular one was chosen.
How to use
First, add the necessary scripts. You’ll need the MooTools 1.2 core and InputPlaceholder.js.
Optionally, define the style for the inputs when the placeholder is activated:
<style type="text/css" media="screen"> .input_placeholder { color: #999; } </style>
If you decide to use the placeholder attribute directly, your markup should look like this
<input type="text" name="email" value="" id="email" placeholder="Email" /> <input type="text" name="name" value="" id="name" placeholder="Name" />
or, the more accessible approach with labels:
<label for="email" class="placeholder">Email</label> <input type="text" name="email" value="" id="email" /> <label for="name" class="placeholder">Name</label> <input type="text" name="name" value="" id="email" />
Finally, instantiate the PlaceholderInput class in a domready event:
window.addEvent('domready', function(){ // for markup #1 $$('input[placeholder]').each(function(el){ new PlaceholderInput(el); }); // for markup #2 $$('label.placeholder').each(function(el){ var target = $pick($(el.get('for')), el.getNext()); if (target && (target.get('type') == 'text' || target.get('tag') == 'textarea')){ target.set('placeholder', el.get('text')); el.destroy(); new PlaceholderInput(target); } }); });
Demo
Click here to see it in action