You can do this without Javascript. Just use a <label>
tag like this:
<label class="placeholder" for="name">Name</label>
<input type="text" id="name">
By using the for
and id
attributes when clicking on the label, browser will switch focus to the linked form field. Then You can for example hide the placeholder by listening on the focus
event in JavaScript. You will need to style the placeholder label to use position: absolute
. See live example (scroll down for some forms).
The above method of defining placeholder text has some advantages:
- You actually define a label for a field. This probably can help accessibility.
- You separate form field's value and placeholder text, so You can support forms that are partially filled.
- You can support more browsers than by using the
placeholder
attribute. - You can style the
label
tag however You like, which is not so easy for theplaceholder
attribute. You can even use CSS or JS animations!