Make links focusable (or use real buttons)

When creating functionality that depends on JavaScript, many use a simple link (a element) to create a trigger for the function – you click it and something happens.

That may be ok, though often it would be more appropriate to use <button type="button">Do something</button> or <input type="button" value="Do something" />.

What is not ok is inserting an a element without giving it a non-empty href attribute, i.e. <a href="#">Do something</a>. Without a non-empty href attribute, the “link” will not be focusable and cannot be activated from a keyboard.

An example of this can be seen at Stack Overflow, a site many will be familiar with. Next to each question and answer is a set of two arrows for voting up/down. The markup for those arrows looks like this:

<a class="vote-up-off" title="…">up vote</a>
<span class="vote-count-post">0</span>
<a class="vote-down-off" title="…">down vote</a>

The absence of an href attribute makes these a elements unfocusable. This can be fixed easily by changing the markup to this:

<a href="#" class="vote-up-off" title="…">up vote</a>
<span class="vote-count-post">0</span>
<a href="#" class="vote-down-off" title="…">down vote</a>

However, in this case I would suggest dropping the a elements completely and using real buttons instead, since that is semantically more in line with what the arrows are:

<button type="button" class="vote-up-off" title="…">up vote</button>
<span class="vote-count-post">0</span>
<button type="button" class="vote-down-off" title="…">down vote</button>

You can then use CSS to style the buttons to look the way you want, they will be fully accessible to both keyboard and mouse users, and your markup will be a bit more semantic.

If there will be no fallback for when JavaScript is missing, these elements should of course be inserted with JavaScript, regardless of whether you use a or button.

This post is a Quick Tip. Background info is available in Quick Tips for web developers and web designers.

Posted on April 20, 2011 in Accessibility, JavaScript, Quick Tips

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.