This is a memo on how to click elements with keyboard shortcuts in JavaScript. It uses the addEventListener(‘keyup’) method and event’s e.keyCode and e.ctrlKey.
The code below demonstrates using JavaScript to execute RUN (script execution) on w3schools.com with a keyboard shortcut.
I was thinking it would be nice if I could save + execute code with Ctrl+Enter.
function doc_keyUp(e) {
if (e.ctrlKey && e.keyCode == 13) {
document.querySelector('body > div.trytopnav > div > button').click()
}
}
document.addEventListener('keyup', doc_keyUp, false);
You can try it on URLs like this:
- [Tryit Editor v3.5](https://www.w3schools.com/css/tryit.asp?filename=trycss_tooltip_right)
function doc_keyUp(e) { if (e.ctrlKey && e.keyCode == 13) { document.querySelector(‘body > div.trytopnav > div > button’).click() } } document.addEventListener(‘keyup’, doc_keyUp, false);
It was my first time implementing a custom keyboard shortcut, so I was a bit confused, but I managed it.
References:
- [Javascript Char Codes (Key Codes) - Cambia Research](https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes)
- [scripting - How can I add a JavaScript keyboard shortcut to an existing JavaScript Function? - Stack Overflow](https://stackoverflow.com/questions/2511388/how-can-i-add-a-javascript-keyboard-shortcut-to-an-existing-javascript-function)