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:

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:

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:

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:

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:

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: