Making a clickable <div> accessible through tab structure?

lfitzgibbons picture lfitzgibbons · Sep 18, 2015 · Viewed 34.8k times · Source

So I am working on a project that requires a <div> with an onclick event. I've got the main functionality working, but there is one problem. I need the onclick event to happen when the user tabs to the <div> and presses enter. I added a tabindex to the <div> which allows it to gain focus, but nothing happens when the user presses enter (or any other key).

Can anyone help me with this? Or is what I want not even possible?

Here is a jsfiddle demonstrating my problem. http://jsfiddle.net/logiwan992/suwq7r09/

Thank you in advance for any help.

Answer

Daniel Beck picture Daniel Beck · Sep 18, 2015

I note the question is tagged WCAG and "accessibility".

The answer to your question is therefore "don't do that." The other answers on this page will all work fine, for everyone except the people who need it to work, i.e. those using screenreaders or other assistive technology. None of the javascript-based solutions here are WCAG compliant.

What you want is a <button>. That gives you your tabindex and keyboard control for free.

You can also force a <div> to work like a <button> by adding ARIA markup (though it's better and easier to just use the tag that already does what you need it to do.)

If absolutely necessary, a good introduction to using ARIA for pseudo-buttons is here: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role

The gist of it is, you need to add the role="button" attribute, and manage the state of the aria-pressed attribute manually (by capturing key events and clicks in javascript; other answers have covered this pretty thoroughly so I won't repeat the details)