How to use HTML accesskey

Overview

In this shot, we will learn how to focus an HTML DOM element without clicking the event or using a mouse. We will create a unique shortcut key to focus a DOM element. An accesskey is a keyboard key assigned to a DOM element.

DOM elements can be any elements on an HTML page like paragraphs, buttons, body, etc.

Usage

How to use the shortcut key in different browsers:

Windows:

  1. Internet Explorer, Chrome, Safari, Opera 15+: "Alt + accesskey"
  2. Opera prior to version 15: "Shift + Esc + accesskey"
  3. Firefox: "Alt + Shift + accesskey"

Mac:

  1. Chrome, Safari, Firefox: "Control + Option + accesskey"

Linux:

  1. Chrome: "Alt + accesskey"
  2. Firefox: "Alt + Shift + accesskey"

Code

Before you press the accesskey, click on the HTML page text to make the Educative window active and then perform the accesskey operation.

Code explanation

We’ll create a shortcut key to activate the DOM element in the above HTML and JavaScript code.

  • In line 5, in the <body> tag of the HTML page, we define an anchor tag. When we click it, it will take us to www.abc.com, and we will do this with the assigned accesskey ‘w’.

  • In line 10, at the end of the <body> tag, we write JavaScript code to assign a unique accesskey ‘w’. We use document.getElementById() to get the DOM element and assign the accesskey ‘w’ using the .accessKey property.

Output

When we press “alt + w”, we see that the link www.abc.com has been activated without clicking the link.

Troubleshooting

  • In the Educative output window, click on the HTML page and then press the “Alt + w” keys.
  • If it is still not working, you may be using a different browser. Try with the keys other than “Alt” if you are on a different browser.

Free Resources