When you want to make an element on a web page clickable in order to trigger a JavaScript function, the best option is to use an element that has native support for keyboard interaction. In most cases a button (either <input type="button" />
or <button type="button"></button>
) is the most appropriate element. It lets everybody trigger your function, whether they use a mouse or not.
Unfortunately, many (maybe even most) developers do not use the correct HTML elements for this. Instead they often use elements that have no native support for keyboard interaction, like span
, div
or li
. A slightly better choice is the a
element since it can receive keyboard focus as long as it has a non-empty href
attribute (i.e. <a href="#">Click me</a>
). But it isn’t really a link anymore since it acts like a button and doesn’t lead anywhere.
What do I suggest then? There are two options:
- Use real buttons and style them so they look the way you need them to look.
- If you simply cannot or will not use real buttons, make sure your fake buttons can be focused and activated without using a mouse.
Posted in Accessibility, JavaScript.
Copyright © Roger Johansson