Command/Control: giving OS aware keybinding hints

As someone who writes a lot of web-based documentation for using computers, it’s often useful to give people hints about keybindings which could make their lives easier. However, this is tricky when it comes to the control key/command key keybinding convention on macOS vs Windows/Linux.

In the past, I’ve just written things like:

To save the file, hit CTRL+S to save (or +S if you’re on macOS)

which gets really tedious when you have to repeat it every time.

So, I wrote a little bit of javascript which

  1. scans the document for any control elements
  2. if it detects1 you’re viewing the site on macOS, changes it to

It actually searches for all of control, command, ctrl, ctl or cmd and “normalises” them to (macOS) or CTRL (otherwise).

On the off chance that I actually don’t want it to do this, the script will skip any <kbd> element with a nopretty class.

If you’re interested, the script looks like this:

window.addEventListener('DOMContentLoaded', (event) => {

  // replace all these with the appropriate modifier for the platform
  let modKeys = ["control", "command", "ctrl", "ctl", "cmd"];

  let modifier = navigator.appVersion.indexOf("Mac")!=-1 ? "⌘" : "CTRL";

  for (const kbdElement of document.querySelectorAll("kbd")) {
	if (modKeys.includes(kbdElement.textContent.toLowerCase()) && !kbdElement.classList.contains("nopretty")){
	  kbdElement.textContent = modifier;
	}
  }
});

In case I make any tweaks, you can always find the latest version in my blog source on GitHub.

  1. it’ll work in most cases; foolproof OS autodetection is really hard 

github twitter vimeo graduation-cap rss envelope search vial coffee heart creative-commons creative-commons-by creative-commons-nc creative-commons-sa