Accessibility in JavaScript Applications

Focus Event Handling in the Dropdown

Marcy Sutton Todd

Marcy Sutton Todd

Principle Studios
Accessibility in JavaScript Applications

Check out a free preview of the full Accessibility in JavaScript Applications course

The "Focus Event Handling in the Dropdown" 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 adds focus event handling to the dropdown to manage focus when navigating over links using only the keyboard.


Transcript from the "Focus Event Handling in the Dropdown" Lesson

>> Marcy Sutton: So, our list is starting to look pretty good. I've got some relationships between the button and the drop down. The mechanics of what I want to happen are, when I click on this button, I want to change the state so that it will toggle, it being open and closed.

Because I could click the same button and it should just open and close. When I open it, I want to send focus to the first item in the drop down. Maybe there, I mean, theoretically, I've seen especially in angular applications where maybe the button and the list are in completely different parts of the DOM.

And that's why it's important to send focus to that drop down when it opens because you need to get the user into the right spot. So, the click handler, I am going to call this set IsOpen, I get my casing right. Set IsOpen and just going to toggle IsOpen.

And that should at least bind the click part of this. The drop down list is what I'm going to toggle the state, based on. So, I added a string for this className, I'm actually going to change it to take some arguments here. So className, if I wrap this in curly braces and add this Tilda character to start a template literal, that's what that's called in JavaScript.

Then I can add a string and I can also add some dynamic stuff in here. So if I add dollar sign, curly braces, I've kind of escaped out of the string and I can put logic in here. This is where this whole mechanics of react in adding these attributes, that's why I like it so much.

So I've got drop down list. I want to say if it's open, I'm gonna add, if the state variable is open, I'm gonna add a class called active. And if it's not, this is a ternary operator here so I can in line have like a NFL conditional. If it's not being toggled to be open, I'm gonna pass it an empty string, because I don't want it to add a CSS class.

So if I save that and I go back to the browser, I can click it, so I've got this most basic behavior and this is where most people stop. Sadly, like getting a button element to toggle would be a huge win. I can at least do that, but I'm not sending focus into the items.

This is pretty good if the list is right next to the button. So in that case like that's pretty good, but I think I can do a little better by forwarding you to this first item. And then the Escape key, I wanna bind to close it. It's also debatable whether you wanna use a focus trap here to trap focus.

That's what GitHub did. We're not gonna go that far but that's a decision that you could make, whether you want to make the user make a choice before they can move on. It's sort of subjective. So let's go back here. And I'm gonna add an escape key listener.

So let's do onKeyUp. Take your advice, Amy, and we will add another function here. So let's do,
>> Marcy Sutton: I'm going to call it key handler, because the the handler function doesn't. It's just a function. It'll be called no matter what he you hit. And so I'm going to go add that right here with const keyHandler.

I'm gonna add it in the event argument here, so that I can get a handle on what key did you actually press. And something I do a lot here is I'll do console log event.key code. I think there's event.key, there's different things that you can do. And when we get into the automated testing section, this will become more important.

But I'm just going to do event.key code, so that way when I work on this and I open the developer tools, and I get over to, let's go back. The skip link to get to the main content is pretty useful. So if I hit the Escape key, that's 27.

If I hit Enter, that's 13, but the escape one is the one that we really want. So I'm gonna go back over here and say, if event.key code is 27 with the triple equals, then I can start and do, I can do things to handle the Escape key.

Let's say we could, I'm gonna add one more thing here. If it is open, then I wanna close it. That's that's when the Escape key's relevant. I don't want Escape to be the toggle, just because that's not really a convention. So I could do setIsOpen to false, just tell it, all right, you're done.

>> Speaker 2: Key code is actually deprecated so you should use key.
>> Marcy Sutton: Key, okay.
>> Speaker 2: Apparently.
>> Marcy Sutton: Thank you. So that's where I've just been doing the thing for so long. So let's do event.key and let's go log that and see. I think I would have had to change that eventually anyway because that doesn't work for automated testing.

But old habits die hard. [LAUGH] So let's go. The nice thing I've got Gatsby Develop running, so it hot reloaded the page and now I should be able to just hit escape. So key is the string name of the key, not the key code. I think there's another, I think it's event.code maybe for the key code.

So in here, we can just say, event.key equals escape. Event.code might be a little bit more reliable. Just keep that, I think that should be the same. So, now if I hit escape it has matched my keyword interaction with the code to handle it and I can tell it to do things like change state.

So, now we've got the escape key part working. The last thing to, before we break will be to add that focus into the first item. So I've got a ref on the list. And this is again a bit of a subjective thing, so one thing I could do here would be to add a tab index of negative one.

That would make this list itself focusible. But I found through user testing and research, that sending focus to rapper elements is actually not the best. It's better to send focus to the first interactive thing, because then you could hit Enter, you'd be there in the right spot. If a user is zoomed way in and their focus outline is cut off, it's kind of confusing.

So for that reason, I'm actually not going to send focus to that list item. But where this gets a little tricky is that our first list item is dynamic, and so there's probably multiple ways that you could work around this. For my prototype here, I'm just going to go find that, so I know the general area.

I know that this drop down list is like the rapper element, and I am admittedly going to go hack at this because sometimes that's what you need to do. We need actually do a little bit more set up to be able to interact with this the way that we want.

So I'm gonna use another react thing here called useEffect. This is another react hook that I can pass a callback function. I'm going to make it toggle on this isOpen. So you can pass it any state variable that you're watching. You can also pass it an empty string or sorry, an empty array and it will fire once when the component loads.

So in this stateless functional component, that's really useful, but I'm actually going to watch it based on whether it's open. And I can add a conditional here. So if it is open, and I think in the hook I want, it's just going to pass this in, I don't need to pass it again.

So if it's open, then I'm gonna do stuff. If it's not open, I'm gonna do other stuff. And something I haven't really talked about yet is another convention, is when you open a drop down list, you kind of expect to click outside of it and close. So we can do that in this useEffect hook as well.

So in this isOpen, I'm gonna handle the focus first. So I've got drop down list ref. So when you have a ref, the EPI is to do the ref that you've defined that current. And that will get you the actual element that you can focus on. So if I were focusing on the list itself, I could say drop down list ref.current.focus.

In this case, current get's me the actual down element, little trick I found. So I'm just gonna say, query selector. And I don't care if this is dirty, I'm just doing it. I can get that first link in the list. And sometimes that's what you need because the list or the link inside of there if I don't have control over that, but that's where I want to send focus, that'll do it.

So let's go look at that and see how that worked. So that sent my focus into the first item. I don't have any CSS animation here that I would need a delay, but the useEffect hook I found is a really great way to work around animation that could delay that being available to focus on.

So another reason to use reactHooks. So the last thing we'll do is to bind up the functionality to close it when you click outside. So to do that, when it's open, I'm gonna bind just a native JavaScript function, which sometimes you have to do as well. It feels a little gross but I'm just gonna do it.

So outside of the scope of my react application, you can just use vanilla JavaScript, so that's what we're gonna do. I'm gonna say document.addEventListener if it's open. And that's where I'm gonna bind this mouse down. And I'm gonna give it a clickOutsideHandler that I'll define in a second.

And when I change, like if this isOpen state variable changes and it's not open anymore, I want to prevent a memory leak. So I'm going to go remove that event listener, because react isn't gonna clean up these events for me, so I have to manage that myself. Otherwise, so these are native events here in JavaScript.

React is using what's called synthetic event otherwise, and this is something that you end up playing around with a lot, because React has a virtual dome and they are managing events for you so you don't have to worry as much about memory leaks. But once you start doing these funky things, kind of mixing native JavaScript in there, you do have to worry about memory leaks.

And those can cause issues. So let's go define this clickoutsideHandler. I'm going to give it an event. Whether or not I need it, I think I actually do in this case. So if I'm clicking outside of the component that I know about, like I can ask it, like am I clicking, and is the event target matching anything that I know about in this component.

And if it doesn't, that's when I'm gonna close. So if, and the thing we're gonna work with here is, this event object from JavaScript is magical because it will tell you what element you clicked on, what element you're dealing with here. So if I say dropdownListRef, if that element contains, so that's one use case, the actual.

So if I click anywhere outside of this list or the toggle button, so both of those because they're separate elements, like if I click out here somewhere, that's when I want this to match. So I'm gonna do both cases. I'm going to do activator and I'm gonna wrap my code here.

ActivatorRef.current.contains If it's either one of those, I'm just going to say, all right, skip it, don't do anything. Just return and that will just like pass over these. Leave it like just drop the event. Don't do anything. But otherwise, I'm gonna say, set is open to false and close it.

So my useEffect, I can do two things, handle focus when it opens or when a state thing changes. I can also do these kind of hacky events. Okay, what did I miss? I missed part of this function. So the arrow function is replacing the word function, and it's pretty awesome for events.

Okay, so now if I click anywhere out here, I can close it and I can hit the Escape key. So you will notice my focus outline is suppressed, and we talked about focus visible earlier. That's something I actually have in here. So if I use the mouse, I don't see a focus outline.

As soon as I use the keyboard again, it will show the focus outline. So it's reacting to the users what we call input modality. So yeah, that is our drop down component.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now