As someone who writes a lot of web-baseddocumentation forusingcomputers, 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
- scans the document for any control elements
- if it detects[1] 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.
it’ll work in most cases; foolproof OS autodetection is really hard ↩︎