A web page is very much a click- (or tap-) friendly medium, but that doesn’t mean you can’t build some keyboard support into your interface. For example, adding the tabindex="0"
attribute to any HTML tag automatically makes that element “tabbable” (meaning a user can set the focus on that element by tapping the Tab key one or more times).
Another good example is a button that you feature on most or all of your pages. In that case, you can set up a keyboard shortcut that enables a user to execute the button by pressing a key or key combination.
You define a keyboard shortcut for a web page by setting up an event handler for the document
object’s keydown
event (which fires when the user presses, but hasn’t yet released, a key). Depending on the type of shortcut, you might also be able to define the shortcut using the document
object’s keyup
event (which fires when the user releases a pressed key). Your event handler needs to look for two kinds of keys:
- Special keys: These include the Alt, Ctrl (or Control on a Mac), Shift, and Meta (that is, Cmd on a Mac) keys. When the user presses a special key, the KeyboardEvent object sets one of the following properties to
true
:altKey
(for Alt),ctrlKey
(for Ctrl or Control),shiftKey
(for Shift), ormetaKey
(for Cmd). - Any other key: These include the letters, numbers, and symbols on a typical keyboard. In this case, the pressed key is returned as the KeyboardEvent object’s
key
property.
Here’s an example:
This example sets up the Ctrl+Shift+B shortcut to run the button. (Note that since my example runs inside an iFrame, you probably need to click inside the Results box before the shortcut key will work.) Let’s take a look the JavaScript:
var btn = document.querySelector('.btn');
button
element and stores it in the btn
variable.
btn.addEventListener('click', function(e) {
btn
element.
btn.innerText = 'Thanks!';
setTimeout(resetButton, 3000);
resetButton
function after 3 seconds.
document.addEventListener('keydown', function(e) {
if(e.ctrlKey && e.shiftKey && e.key === 'B') {
btn.click();
btn
element's click
event.
function resetButton() {…
blur
event, just in case the button was clicked.