Quick tip on placeholders and accessibility

Ah, the placeholder. The best thing to happen to the input box since…well, nothing ever happens to the input box.

Form with placeholder

That is, unless you’re supporting IE9. In which case you have problems.

Form without placeholder support

There are ways around this, the most widely used being jquery-placeholder. The problem with approaches like this is they generally rely on putting actual text in the input box and hacking common value retrievers to report that they’re empty. For example, jquery-placeholder will make sure $('.text-box').val() returns empty. But querying the value with another DOM library or plain old JavaScript may give you the placeholder text as the current value. Which is bad.

The placeholder can also trick you into thinking you can skip having a label for the form element. For accessibility reasons, you can’t. Screen readers need those things, even if they aren’t visible on the screen. Technically you can do an aria-label on the element itself instead, but then you still have unlabeled form fields with IE9.

Here’s my solution, for what its worth.

First, I give form elements labels and hide them so they only get picked up by screen readers. Bootstrap has a handy sr-only class just for this.

1
2
<label for="email" class="sr-only">Email Address (optional)</label>
<input id="email" class="form-control" type="email" name="email" size="30" placeholder="Email Address (optional)" />

Next a little JavaScript to detect whether placeholder is supported. If not, it removes the sr-only class so the label will be visible.

1
2
3
if (!('placeholder' in document.createElement('input'))) {
$("label").removeClass("sr-only");
}

Form without placeholder support

That’s a little confusing, but it’s basically a tiny unit test for placeholder. So IE9 or whatever horror show from yesteryear without placeholder support gets labels, everybody else gets placeholders, and screen readers are a-OK.