While keystrokes aren’t the most common element to represent, they’re frequently involved, and they get first-class treatment in order to make it easier to discuss shortcuts related to developer productivity.

The Basics

kbd can be used to communicate pressing specific keys on the keyboard. For example to represent the ‘Command’ and ‘S’ keys, you can use the kbd element and rest assured that it will render a nice CMD + S representation. While this technically works, there is a better option.

Typing the opening and closing <kbd> around every key is clunky to type. Plus, wouldn’t it be nice to use the corresponding symbols for the keys that have them? Yes and no. It looks nicer, but using symbols isn’t accessible, and they don’t always correlate across operating systems. So that means including alternate/title text.

The Helper

<%= keys :opt, :cmd, :s %>
Figure 1

The keys helper method takes symbolized representations of keys and intelligently converts them to the relevant markup.

↩︎

Enter the keys helper which accepts a comma-delimited list of symbols or strings and intelligentally concatenates them as HTML kbd elements while swapping them for symbols where appropriate. When a symbol is substituted, it uses the abbr element in conjunction with the symbol for accessibility. (Figures 1 & 2)

With the keys helper, not only are the kbd elements rendered as keys, but it intelligently translates and concatenates keys so that the shortcut feels like a combined shortcut. Even better, since it’s translating keys to symbols, it’s also smart enough to include the title attribute and show the name of the key when a symbol is used.

When it’s rendered inline, the above code would appear as: + S, and as a fun bonus, if you “click” the shortcut, the keys are all “pressed” together to reinforce that it’s a shortcut involving all the keys.

<span class="shortcut" title="Command/Super/Windows+S"><kbd><abbr title="Command/Super/Windows"></abbr></kbd> + <kbd>S</kbd></span>
Figure 2

The keys helper groups the resulting HTML elements with a span, substitutes symbols where relevant, and adds alternate text and titles.

↩︎

The Special Keys

When writing, inserting a symbol like that isn’t readily available with a keystroke can be tedious. So, the keys helper makes it all work by supporting auto-translation of some common symbol keys.11It would be really nice to auto-detect the visitor’s operating system and swap some key symbols and titles, but that will have to wait. For now, ensuring the title text includes the Linux and Windows variants.

Symbol Glyph Title
:cmd Command/Super/Windows
:ctrl Control
:del Delete/Backspace
:esc Escape
:fdel Forward Delete/Delete
:fn Fn Function
:opt Option/Alt
:return Return or Enter
:shift Shift
:tab Tab
:up Up
:down Down
:right Right
:left Left
Figure 3

When used with the keys helper, these will be translated to the corresponding glyphs and titles.

↩︎