JavaScript Keyboard Shortcut Element Click

Clicking Elements with Keyboard Shortcuts in JavaScript

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.

Shou Arisaka
2 min read
Oct 28, 2025

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)
Tampermonkey version: ``` // ==UserScript== // @name ctrl+Enter equivalent to click "Run" // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author https://yuis-programming.com // @match https://www.w3schools.com/* // @grant none // ==/UserScript==

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)

Share this article

Shou Arisaka Oct 28, 2025

🔗 Copy Links