DEV Community

Summer Rizzo
Summer Rizzo

Posted on

Accessibility Tip: Toggling Focus on or off for Keyboard Accessibility

Hey folks! I wanted to share a quick tip regarding keyboard control accessibility.

It goes without saying that as web developers, our websites and apps should be accessible to everyone! Sometimes, though, it can be an oversight to remove something like focus outlines that seems unattractive to those of us who don't require it. When I first started out, removing focus outlines on buttons was often the first thing I did. Of course, once I realized they were for keyboard accessibility, I left it on - but I recently found out about a solution that allows us to have our cake and eat it too :)

In your root JS file, add the following lines:

// Adds keyboard-accessible class to the <body> of the page in CSS
document.addEventListener('keydown', (e) => {
    if (e.key === 'Tab') {
        document.body.classList.add(styles.keyboardAccessible);
    }
});

// Removes class from body in CSS
document.addEventListener('mousedown', () => {
    document.body.classList.remove(styles.keyboardAccessible);
});

For some explanation, the former event listener reacts to someone pressing the "Tab" key, which activates the keyboard accessible class. Tab is the key that those who need keyboard accessibility use to navigate the page.

The second one turns it off. It uses "mouse down" as the event because it's an event that, obviously, has no relation to the keyboard - usually people who need keyboard accessibility need it because they are unable to easily use a mouse. And, in the case that someone needed to navigate with the keyboard again after turning it off, pressing Tab will reactivate the class.

Now, head on over to your root CSS File and add these rules:

body.keyboardAccessible *:focus {
    outline: 2px solid red; 
}

body:not(.keyboardAccessible) *:focus {
    outline: 0;
}

These are the classes that are activated/de-activated when pressing the Tab key or mouse respectively. The outline doesn't have to red, but it does need to have adequate contrast with the elements it is against (WCAG recommends a contrast ratio of at least 3.1 for graphical user interfaces).

Voila! As another benefit, checking to make sure this works appropriately after you implement it is a good way to see how someone using keyboard controls navigates through your page. It may help when considering an accessible layout for your site or web app.

With <3, happy coding!

Top comments (1)

Collapse
 
coryvia profile image
Extra Syrup

Great article!