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:
- Internet Explorer, Chrome, Safari, Opera 15+: "Alt +
accesskey" - Opera prior to version 15: "Shift + Esc +
accesskey" - Firefox: "Alt + Shift +
accesskey"
Mac:
- Chrome, Safari, Firefox: "Control + Option +
accesskey"
Linux:
- Chrome: "Alt +
accesskey" - 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 assignedaccesskey ‘w’. -
In line 10, at the end of the
<body>tag, we write JavaScript code to assign a uniqueaccesskey ‘w’. We usedocument.getElementById()to get the DOM element and assign theaccesskey ‘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.