Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

HTML-only Keyboard Shortcuts

Often you may need to incorporate keyboard shortcuts into your website. And in modern web applications, keyboard shortcuts have become an integral part of the user experience.

If used properly, keyboard shortcuts for things can improve the user’s workflow and in turn, overall experience.

Now, traditionally, if you want to use keyboard shortcuts, you may reach for the solution that involves JavaScript keyboard event listeners. I have discussed this in detail in this article if you’re interested in reading about it.

But I recently got to know about a way that lets you set up keyboard shortcuts only HTML. No JavaScript is needed!

The accesskey global attribute

There’s a global HTML attribute called accesskey that lets you provide a hint for generating a keyboard shortcut for the current element.

Here’s an example.

<a 
    href="/dashboard" 
    title="Dashboard" 
    accesskey="g"
>
    Dashboard
</a>

As you can tell, we can set the accesskey attribute to a hyperlink and assign a key to it.

Now, the accesskey attribute works with the combination of another key which is platform-specific.

So, if you’re on Windows/Linux, you can virtually click the “Dashboard” link by pressing Alt + g.

For macOS, this will be Option + g.

And that’s how you can implement HTML-only keyboard shortcuts.

You can set accesskey up for other HTML elements as well. For instance, you set up a keyboard shortcut on a button to click it virtually.

A practical example

I have setup an accesskey shortcut for the search on this blog that you can access by pressing Alt + k together.

accesskey example

So, go ahead and try it yourself!

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?