简体   繁体   中英

Count how many keys are pressed at the same time in JavaScript

Is it possible to count how many keys are pressed at the same time? I've come quite far but I get some unwanted behavior when tabbing away from my browser window. If I hold down x number of keys when tabbing away from the browser window and then release the keys in a different window the numKeys array stays the same when I tab back to the browser window. Maybe you can check how many keys are pressed when returning to the browser window or something?

My code so far:

var numKeys = [];

$(document).keydown(function(e){
    if(numKeys.indexOf(e.keyCode) == -1){
        numKeys.push(e.keyCode);
    }
    document.getElementById('test').innerHTML = numKeys.length;
});

$(document).keyup(function(e){
    if(numKeys.indexOf(e.keyCode) > -1){
        var index = numKeys.indexOf(e.keyCode);
        if(index > -1){ numKeys.splice(index, 1); }
    }
    document.getElementById('test').innerHTML = numKeys.length;
});

try this (UPDATE):

var cpt = 0;
var codes = "";
$(function () {
    $(document).keydown(function (e) {
        if (codes.indexOf(";" + e.keyCode + ";") == -1) {
            cpt++;
            codes += ";" + e.keyCode + ";";
        }
    });
    $(document).keyup(function (e) {
        var tmp = ";" + e.keyCode + ";";
        if (codes.indexOf(tmp) != -1) {
            cpt--;
            var part1 = codes.substring(0,codes.indexOf(tmp));
            var part2 = codes.substring(codes.indexOf(tmp)+tmp.length );
            codes=part1+part2;
        }
    });
});

The new Working ;) link : FIDDLE

A simple solution to your problem would be to clear the keys pressed when the user leaves the tab. You can use the window.onblur event like this:

window.onblur = function () {
    numKeys = [];
};

Demo .

Note that this solution will not be aware of keys you press in another window. (For example, you press "up" in another window, and then select this window again)

Let's keep it very simple. Idea is to set the keys with the object being event.keyCode to true on keydown , and delete on keyup . Then count the instances of true in keys ,

var keys = [];
$(function () {
    $(document).keydown(function (event) {
        keys[event.keyCode] = true;

        var count = 0;
        for (var i = 0; i < keys.length; i++) {
            if (keys[i]) count++;
        }
        console.log(count);
    });

    $(document).keyup(function (e) {
        delete keys[e.keyCode];
    });
});

I decided to share my snippet mentioned and linked just a few minutes before in the comments above. But, just to make it clear, I'm finding hard to press / accept by the keyboard more than four, maybe five keys at the same time and that's why all these attempts might be useless :)

window.onload = function(){

  var a = [];
  var log = document.getElementById("keys");

  document.body.onkeydown = function(event){
    var keyCode = ('which' in event) ? event.which : event.keyCode;
    if(a.indexOf(keyCode) == -1) a.push(keyCode);
    log.innerHTML = a.length + " | " + a.join();
    return false;
  };  

  document.body.onkeyup = function(event){
    a = [];
    log.innerHTML = a.join();
  };

};

Working jsBin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM