How can I add a keyboard shortcut to an existing JavaScript Function?

An event handler for the document’s keyup event seems like an appropriate solution.

Note: KeyboardEvent.keyCode was deprecated in favor of key.

// define a handler
function doc_keyUp(e) {

    // this would test for whichever key is 40 (down arrow) and the ctrl key at the same time
    if (e.ctrlKey && e.key === 'ArrowDown') {
        // call your function to do the thing
        pauseSound();
    }
}
// register the handler 
document.addEventListener('keyup', doc_keyUp, false);

Leave a Comment