Responding to keyboard input
Create event handlers to enable user interface components to respond to keyboard input.
User interface components often need to be programmed to act upon keyboard input events initiated by the user. This requires the use of event handlers.
Meeting the Web Accessibility Standard
When all user interface components can be operated via keyboard, this meets WCAG 2 Success Criterion 2.1.1 Keyboard (Level A).
Event handlers
Event handlers are bits of JavaScript code that are executed when an event occurs.
For an introduction to events and using event handlers, see Introduction to Events — MDN Web Docs.
For more information on handling keyboard events, see:
- Introduction to Keyboard Events in JavaScript — Section
- KeyboardEvent — Web APIs — MDN Web Docs
- Mouse-specific events — CSS and JavaScript accessibility best practices — MDN Web Docs.
Keyboard-specific event handlers
Some event handlers are device dependent and fire only when a mouse or a keyboard is used to interact with web content.
The keyboard-specific event handlers are:
onkeydown
— fires when a key is pressedonkeyup
— fires when a key is releasedonkeypress
— this event handler is deprecated and should not be used.
If device-dependent handlers are used, make sure to match each keyboard-specific handler with its related mouse-specific handler, and vice versa.
For more information, see:
- SCR20: Using both keyboard and other device-specific functions — WCAG 2 — W3C
- Mouse-specific events — CSS and JavaScript accessibility best practices — MDN Web Docs.
Device-independent event handlers
Other event handlers are called logical, generic or device independent because they respond to the basic nature of the event that a user initiates, and not the device that they use to cause it.
Device-independent event handlers include:
onfocus
— fires when a focusable element receives focusonblur
— fires when a focusable element loses focusonclick
— fires when a mouse is clicked or a natively focusable element, such as<button>
, is activated or tapped with a finger or stylus (see Ononclick
below).
Note: Try to use device-independent event handlers as much as possible.
Using onclick
With natively focusable elements
If a natively focusable element like <button>
or <input type="checkbox">
is used to build a custom control, keyboard operability is built in through onclick
.
The onclick
event handler will fire when:
- a mouse is clicked
- the Enter or Space key is pressed
- the element is tapped with a finger.
With non-focusable elements
If a non-focusable element like a <div>
is used, it needs to be made focusable — and both of the following event handlers are required to provide pointer and keyboard support:
onclick
onkeydown
.