In HTML you can set your own shortcut keys in a form:
<label accesskey="n">name</label>
But, how would be the preferred form to display the "n" to make the user notice that this letter is the shortcut? The old convention is to display it underlined, which in HTML should be like this:
<label accesskey="n"><u>n</u>ame</label>
... but since <u>
tags are discouraged in HTML5, is there a standard (or conventional) form to display this kind of shortcut characters in a HTML page?
P.S.: I know I can set a specific style through something like <span class="mystyle">n</span>
, but I'm asking for an easier solution - preferrably some specific HTML tag.
One option is to use CSS to append the accesskey using CSS.
[accesskey]::after {
content: " [" attr(accesskey) "]";
}
<label accesskey="n">name</label>
The only other option I can see (if you don't want to manually highlight the accesskey itself) is to use JavaScript to wrap the key.
// This uses ES6 syntax
// [].find() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
// NodeList.forEach() - https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
// ChildNode.replaceWith() - https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
function parseHTML(htmlString) {
return document.createRange().createContextualFragment(htmlString);
}
function findFirstTextNode(element) {
return Array.prototype.find.call(element.childNodes, (node) => (
node.nodeType === Node.TEXT_NODE
));
}
// Extremely basic implementation
function sprintf(string, ...args) {
return args.reduce(
(rendered, item) => rendered.replace("%s", item),
string
);
}
function highlightAccessKey(
el,
replaceString = "<span class=\"accesskey\">%s</span>",
appendString = "<span class=\"accesskey\">[%s]</span>"
) {
let accesskey = el.getAttribute("accesskey");
let textNode = findFirstTextNode(el);
if (textNode) {
let text = textNode.textContent;
let index = text.indexOf(accesskey);
if (index > -1) {
text = (
text.slice(0, index)
+ sprintf(replaceString, accesskey)
+ text.slice(index + accesskey.length)
);
} else {
text += sprintf(appendString, accesskey);
}
textNode.replaceWith(parseHTML(text));
} else {
el.appendChild(parseHTML(sprintf(appendString, accesskey)));
}
}
document
.querySelectorAll("[accesskey]")
.forEach((el) => highlightAccessKey(el));
.accesskey {
text-decoration: underline;
}
<label accesskey="n">name</label>
Sadly, there's not an out-of-the-box solution.
You could use the title
attribute to display the shortcut when the element is hovered:
<label accesskey="n" title="shortcut-key: n">name</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With