Check out a free preview of the full Accessibility in JavaScript Applications course:
The "Focus Events" Lesson is part of the full, Accessibility in JavaScript Applications course featured in this preview video. Here's what you'd learn in this lesson:

Marcy demonstrates how to make custom controls interactive by adding focus events, and analyzes the choice of HTML elements when planning out interactive parts of a page.

Get Unlimited Access Now

Transcript from the "Focus Events" Lesson

[00:00:00]
>> Marcy Sutton: We've added accessibility information and focus ability, but what about events? What if you wanna do something with that button? It's not just gonna sit there and not do anything. If I added a click event to an element like a div, I could just add an onClick. This is react code here on the left.

[00:00:16] But a div will not react to a click event by default. We actually have to make it work with the keyboard with a key listener. So here I have onKeyDown, and I can tab on to this button. The react code here is not bound. So if you're using Vanilla JavaScript, you could write a, little JavaScript function and have it react to these events.

[00:00:43] Just know that if you choose a button element instead, you could skip a lot of that work. Look at how many lines it takes to make an accessible div and you need the two events. Whereas, with a button element it already has the roll of button, it already has focus ability.

[00:01:00] And I can use a click handler just the one. So a button will fire with a click event, whereas, a div needs both the click and the key listener. So something to pay attention to. Question.
>> Speaker 2: Yeah, so I've read that it's better to do onKeyUp so that people can exit or undo the accidental click

[00:01:21]
>> Marcy Sutton: Yeah, sure.
>> Speaker 2: And I was also curious if onClick does that by default. onClick means when they lift their finger off the key.
>> Marcy Sutton: It's good question. So yeah, good point. There are multiple key listeners. And key up might be the one that you wanna reach for just based on how that will work for the user.

[00:01:44] For our click event with the keyboard, it fires an actual click event. If you really wanted to, you could bind an onMouseDown and an onKeyUp and do slightly different things. I have found that just streamlining it with the one click listener if you can on a button is just easier.

[00:02:03] It's less to manage, you run into less issues with screen reader interaction modes on Windows. So you just wanna make sure that if you're creating interactive things, that you're testing with the keyboard. This is where the keyboard debugging would come in handy for a fully hooked up component.

[00:02:23] Whereas, if you are just clicking with a mouse, you might never know that the div doesn't fire from a key listener.