✎ Technique: Keyboard operable custom controls

Sometimes, design requirements mean that you need to create an interactive element from a base <div> element or a custom element like <my-button> rather than using a native HTML element.

Your element will not be accessible by keyboard unless it is included in focus order and it can be activated using the ENTER and SPACE keys.

Example

Let's consider a <div> element with an id of "button", to which we want to attach JavaScript click events. The first thing we need to do for keyboard accessibility is make it focusable using a tabindex value of 0:


<div id="button" tabindex="0">trigger click event</div>

Now keyboard users will be able to focus it like a standard <button> control. However, the only way to fire the click event is to click the element using the mouse. Unlike <button>s, <div>s don't support keyboard activation by default, so we have to trigger the click event using a custom key binding:


var button = document.getElementById('button');
button.addEventListener('keydown', function(e) {
  if (e.keyCode === 13 || e.keyCode === 32) {
    e.preventDefault();
    this.click();
  }
});

In the above code, we listen to keydown events on our button. If the key code associated with a keydown event matches either the ENTER key (13) or SPACE key (32), we call the button's click method, which simulates a mouse click to the button. To prevent the page from scrolling when the SPACE key is pressed, the default behavior is suppressed.