Note: This is an advanced version of Accordion II, you should complete that question first before attempting this question. This question is not available in Vanilla JavaScript as it will require a fair bit of code to add keyboard interactions without a JavaScript framework.

In Accordion II, we built a functional accordion component that has the necessary WAI-ARIA roles, states, and properties, which is actually pretty accessible. However, we can go one step further and add some optional keyboard interactions.

Requirements

We'll be following a modified subset of the necessary keyboard interactions for accordions:

Notes

Solution

The following explanation assumes you have a good understanding of Accordion II's React solution.

Solution

Listening for Keyboard Events

Firstly it's crucial to know the difference between the keypress vs the keydown event. The keypress event is only fired when a key that produces a character value is pressed down. This would exclude the Up, Down, Home, and End keys which are requirements of this question. The keypress event is also deprecated and shouldn't be used. For these reasons, we should be using the keydown event. We'll add a keydown event listener to the root <div> element.

To know which key is being pressed, we can use event.key or event.code on the event passed to the keydown event callback. There are some differences between event.key vs event.code but for the purposes of this question it doesn't make a difference and can be ignored. We'll just use event.code.