Get a list of all currently pressed keys in Javascript

javascript

Solution

- whenever a key is pressed a `keydown` event will be sent

- whenever a key is released a `keyup` event will be triggered

So you just need to save the keys in an array and check whether your combination is true.

Example

var keys = [];
window.addEventListener("keydown",
    function(e){
        keys[e.keyCode] = true;
        checkCombinations(e);
    },
false);

window.addEventListener('keyup',
    function(e){
        keys[e.keyCode] = false;
    },
false);

function checkCombinations(e){
    if(keys["a".charCodeAt(0)] && e.ctrlKey){
        alert("You're not allowed to mark all content!");
        e.preventDefault();
    }
}

Note that you should use `e.key` instead of `e.keyCode` whenever possible (in this case `var key = {}`, since `e.key` is a string).

Problem

In Javascript, I want to write a function that returns a list of all keys that are currently pressed (so that I can allow the user to create custom keyboard shortcuts.) Is there any way to obtain a list of all currently pressed keys in Javascript?

Original source

Related problems