HTML - Accesskey Attribute (keyboard shortcut)

About

All HTML elements may have the accesskey content attribute set.

The accesskey attribute's value 1) is used by the user agent as a guide for creating a keyboard shortcut that focuses (ie activates) the element.

Syntax

The value must be:

  • an ordered set of unique space-separated tokens
  • that are case-sensitive,
  • each of which must be exactly one Unicode code point in length.

Example

  • Two access key defined:
accesskey="s 0"
  • One
accesskey="A"

Assigned access key by Browsers

  • Chrome / Firefox: Alt + Shift + Key
  • Others: Alt + Key

Advanced

If you want to create advanced keyboard shortcut, you can also use the keydown event (or related wrapping library)

Example:

  • A simple search box form where we want to focus on
<form id="search-form">
     <span id="search-input-container">
          <input type="search" id="search-input" placeholder="Search ..." aria-label="Search for...">
     </span>
</form>
  • The javascript listen to keydown and if the control key and the key / are the one, we focus on the input
var searchInput = document.getElementById('search-input');
// window.parent because this code run in a iframe, otherwise just document
window.parent.addEventListener('keydown', function(event) {
        event.ctrlKey && event.key === '\\' && (event.preventDefault(),searchInput.focus())
})
  • Click Ctrl+\ to focus on the input