Forms: Inputs with initial values acting as labels and HTML5′s placeholder attribute
I’ll be brief. A few years ago, a trend started popping up whereby the label next to a text input (at the time most commonly search fields) would be removed, and instead the default value of the field would be its label. On focus, the input value would be blanked. The result was a cleaner look and really no loss in usability (as well as no loss in accessibility so long as the developer takes care to put the label element in the DOM, but hide it).
The behaviour is common practice now, not only for single-field forms like search inputs, but entire ten-plus field information gathering forms. This is where the problem arrises. If you’re like me and tab between inputs (‘fill in field, hit tab, fill in next field, hit tab, etc), it’s very easy to forget that you need to read the value (acting as a label) in the next field before tabbing into it – as soon as it has focus, you can no longer tell what you’re supposed to be inputting.
The
placeholderattribute should not be used as an alternative to alabel. –HTML5 Draft Spec
Even more recently, the HTML5 spec introduced the placeholder element for inputs. Though the HTML5 spec advises against using a placeholder in place of a label element, it seems common practice to do so, and it tempting even for myself. This would be fine and dandy if it weren’t for the specific implementation of placeholder‘s behaviour in all major browsers: Exactly the same as we saw above, clear on focus. It leads to precisely the same problem as before, but this time natively instead of using a bit of JavaScript.
I’ve created what I believe is the ideal alternate behaviour multiple times in the past with a tiny bit of JavaScript and CSS:
- Position the label for an input directly below it with the same borders/padding so that the text lines up perfectly with what is typed in the input
- Using JavaScript, bind a function on change for the input that checks to see what the value of the input is (after each keystroke), and if it’s anything other than blank, hide the label. If the label is hidden and the input is blank on change (you’ve deleted the contents of the input), show the label.
I’m not completely sure whether the necessary change here is in the behaviour/intended use case of the placeholder attribute or in the code developers are writing in conjunction with their forms. Since it’s highly unlikely the HTML5 spec will dictate such a change at this point, I think the onus is on developers to be more careful with the aesthetics/usability line. If you implement the above properly and with care, you’ll have an accessible form that saves clutter and uses no additional markup.
Every once in a while you encounter a tiny feature of a website that makes your day and improves your perception of the site as a whole drastically.