While browsing the MDN, I came across the access keys page and that was certainly a fun read. I like the idea of having keyboard shortcuts for various buttons and I think it could be useful in some applications.
I was already wiring up a prototype that didn't use any frameworks or CSS and so this was the perfect place to give this plain html and javascript a test drive.
The idea of access keys is to give buttons a specific keyboard shortcut so that when you press the shortcut, it will trigger the button. For example giving a button the access key c will let you do Alt + Shift + c to trigger the button in addition to being able to click it.
This is often used in GUI applications to bypass the mouse. For example in Firefox, you can do Alt + f to trigger the File menu option.
HTML access keys use the Alt + Shift as the modifier. This changes browser to browser and you can look at the MDN page to see what the modifiers are for other browsers.
I originally wrote the code for each button but then abstracted it into a dynamic set up.
const accessKeys = new Set();
accessKeys.add(" ");
accessKeys.add("c");
const buttons = document.querySelectorAll('[role="tab"],[data-dialog]');
buttons.forEach(button => {
let text = button.textContent.trim();
for (let pos=0; pos < text.length; pos++) {
const key = text[pos].toLowerCase();
if (accessKeys.has(key)) {
continue
}
accessKeys.add(key);
button.setAttribute("accesskey", key);
button.innerHTML = `${text.slice(0,pos)}<u>${text[pos]}</u>${text.slice(pos+1)}`;
break;
}
});
The core logic is that I select all the buttons I care about, this could be made general but I narrowed down to specifically buttons I was using to do tabs or ones that were for modals.
Then each button was processed and I figured out if there was a letter that I could use as the access key. I didn't want to have duplicates so I keep track of already used characters. This means that for most buttons, the access key will be the first letter but for some it could be much further down the chain.
If there are too many buttons, a button could end up with no access key.
The key attribute to set is the accesskey attribute. This is set on the button and is a regular html attribute.
I'm using javascript to make it dynamic but the essence can be done in pure html:
<button accesskey="a"><u>A</u>BC</button>
I'm using u tag to do the underlining.
An enhancement would be to make sure special characters don't become access keys but this was more of a test drive so I didn't bother adding any more code.
You can also populate the accessKeys set with the browser specific shortcuts so those don't get used. For example Edge uses Alt + c so I wanted to skip that. That's why it's been added to the accessKeys set.
This works quite well and is relatively intuitive once you know about it. I can see surfacing this information being a pain though. This reminds me of using TUIs so that's probably why I think this is so fun.