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.
We'll be following a modified subset of the necessary keyboard interactions for accordions:
When or is hit and focus is on the accordion header
Enter
Space
Tab: Moves focus to the next focusable element; all focusable elements in the accordion are included in the page sequence.
Tab
Shift + : Moves focus to the previous focusable element; all focusable elements in the accordion are included in the page sequence.
Tab
Tab
Down Arrow: If focus is on an accordion header, moves focus to the next accordion header. If focus is on the last accordion header, either does nothing or moves focus to the first accordion header.
Up Arrow: If focus is on an accordion header, moves focus to the previous accordion header. If focus is on the first accordion header, either does nothing or moves focus to the last accordion header.
Home: When focus is on an accordion header, moves focus to the first accordion header.
End: When focus is on an accordion header, moves focus to the last accordion header.
The following explanation assumes you have a good understanding of Accordion II's React solution.
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.