This tutorial aims to guide you through the process of building UI components that are keyboard-friendly. By the end, you will have a better understanding of how to design and implement components that respond smoothly to keyboard events, and maintain accessible states.
Basic knowledge of HTML, CSS, JavaScript and accessibility guidelines is required to follow this tutorial.
Before diving into the code, let's discuss some key principles to keep in mind:
In JavaScript, there are three key events:
keydown
: This event is fired when a key is pressed.keypress
: This event is fired when a key is pressed and released.keyup
: This event is fired when a key is released.Let's see a practical example of a keyboard-friendly button:
<button id="myButton" tabindex="0" role="button" aria-pressed="false">Click Me!</button>
let button = document.getElementById('myButton');
button.addEventListener('keydown', function(event) {
// 'Enter' or 'Space' is pressed
if(event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
// Toggle 'aria-pressed'
this.setAttribute('aria-pressed', this.getAttribute('aria-pressed') === 'true' ? 'false' : 'true');
}
});
In the above example, we have a button that responds to 'Enter' or 'Space' keypress. The 'aria-pressed' attribute toggles between true and false, representing the pressed state of the button.
In this tutorial, we've learned about keyboard events, how to build accessible UI components, and how to respond to keyboard events. For further learning, explore other ARIA roles and properties and try to build more complex components like modals and dropdowns.
<input type="checkbox" id="myCheckbox" tabindex="0">
let checkbox = document.getElementById('myCheckbox');
checkbox.addEventListener('keydown', function(event) {
if(event.key === 'Enter') {
event.preventDefault();
// Toggle checked state
this.checked = !this.checked;
}
});
This exercise involves more complex coding and understanding of keyboard events. You need to handle 'ArrowDown', 'ArrowUp', and potentially 'Enter' and 'Escape' keys.
This exercise also requires a more advanced understanding of focus management and event handling. You will need to create a modal, manage its 'open' state, and handle the 'Enter' and 'Escape' keys to open and close the modal.