Amar Sagoo

16 July 2007

Clickable control labels for the web

One of my pet peeves in web interfaces has always been that on radio buttons and checkboxes, only the small button itself is clickable. In native Mac and Windows interfaces, you can usually click on the text labels of these controls as well, giving you a much larger target, which, in accordance with Fitts' Law, makes them faster to hit.

Many, or perhaps most, people would probably never notice this difference in behaviour because they have only ever tried clicking on the button proper; the text doesn't visually suggest that it's clickable. But for those of us who are used to this shortcut, the standard web behaviour will catch us out every time. (Actually, I've started to wonder whether I'm the only person on the planet to click on the text labels, since I've never heard anyone else complain about this issue.)

Until a few months ago, I thought this was all just an unfortunate but inevitable limitation of HTML, and that developers found it too much hassle to implement a workaround in JavaScript. Then, I discovered HTML's label element. If you mark up a piece of text as a label and set its for attribute to be the ID of a form control, it becomes the "official" label for that control. The practical effect of this is that in most browsers, clicking the label will actually do something useful. For checkboxes and radio buttons, it will toggle their state, while for text fields, it will put the focus on the field. This works in Internet Explorer 6(!) and 7, Safari (I only checked version 3.0.2), Firefox and Camino. OmniWeb will do it in the upcoming 5.6 release.

So code like the following:

<input
 type="radio"
 name="os"
 id="mac"
 value="mac">
<label
 for="mac">Mac user</label>

<input
 type="radio"
 name="os"
 id="windows"
 value="windows">
<label
 for="windows">Windows user</label>

<input
 type="checkbox"
 name="loving_it"
 id="loving_it">
<label
 for="loving_it">And loving it</label>

results in nice, fully clickable controls like this:

There's also an alternative, simpler syntax that doesn't require using the for and id attributes. Instead, you can just make the label element a parent of the control:

<label>
  <input
   type="radio"
   name="os"
   value="mac">Mac user
</label>

However, this does not work in Internet Explorer 6, so if you want to be inclusive, stick with the more explicit syntax.