'Html accesskey with two or three words
I am using accesskey attribute for button press like accesskey="a"
But I want like this: accesskey="a+b"
Instead of only "a" I want to use "a" and "b"
How to use more than one word for accesskey in html?
Solution 1:[1]
You can do it with javascript.
<button onclick="console.log('save')" data-hotkey="Ctrl+S">Save</button>
<button onclick="console.log('print')" data-hotkey="Alt+P">Print</button>
<button onclick="console.log('debug')" data-hotkey="Ctrl+Alt+D">Debug</button>
<script>
document.addEventListener("keydown", (keyboardEvent) => {
// KeyboardEvent: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
/* You can do some checking to end early for efficiency.
if (!(keyboardEvent.ctrlKey || keyboardEvent.altKey)) {
return
}
*/
[...document.querySelectorAll(`[data-hotkey]`)].forEach(elem => {
const combineKey = elem.dataset.hotkey.split("+")
// check
for (let myKeyStr of combineKey) {
myKeyStr = myKeyStr.toUpperCase()
if (myKeyStr.length > 1) {
if (myKeyStr === "CTRL" && keyboardEvent.ctrlKey) {
continue
}
if (myKeyStr === "ALT" && keyboardEvent.altKey) {
continue
}
}
if (keyboardEvent.key.toUpperCase() !== myKeyStr) {
return
}
}
keyboardEvent.preventDefault() // prevent default behavior. For example: Ctrl+S will save (for OS:Windows)
elem.click()
})
})
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carson |
