0

This thread almost solved my problem: Can jQuery .keypress() detect more than one key at the same time?

However, with the code provieded. If you press CTRL+C to copy some text, and then let go, the number will stay at "1" untill you pressed CTRL and R seperately.

The code:

var keys_count = 0;
var keys = {};

$(document).keydown(function (e) {
    if(keys[e.which]) return;

    keys_count = keys_count + 1;
    keys[e.which] = true;

    printKeys();
});

$(document).keyup(function (e) {
    keys_count = keys_count - 1;
    delete keys[e.which];

    printKeys();
});

function printKeys() {
    $('#out').html(keys_count);
}

Try my example here: http://jsfiddle.net/gFcuU/524/

Any ideas how to avoid this?

I simply want to track, wether the current user is simply typing some letters, or doing a command i.e. CTRL + C, CTRL + A, etc. But maybe there is an easier method, that I've found so far?

Community
  • 1
  • 1
FooBar
  • 5,752
  • 10
  • 44
  • 93
  • founder and creator of jQuery created a great little plugin for hotkeys...takes a lot of manual coding of key codes out of the picture https://github.com/jeresig/jquery.hotkeys – charlietfl Nov 10 '13 at 16:41
  • I don't have an answer but I wrote something similar because I took your question as a challenge. You can try pressing multiple keys. Though there's an issue. If you press for too long It won't clear the array. Anyway. Check my amateur work [Fiddle](http://jsfiddle.net/yVkAJ/) :) – akinuri Nov 10 '13 at 18:00

2 Answers2

2

The simplest thing is to test for event.ctrlKey:

$(document).keydown(function (e) {
    if (e.ctrlKey) {
        $('#ctrl').text("true");
    } else {
        $('#ctrl').text("false");
    }
});

FIDDLE

You can combine this with tests for normal keys also. E.g.:

if (e.ctrlKey && e.which == 67) {

jQuery Event Object API

  • Thank you for this. I will accept this answer as correct, however, the issue still persists on macbooks, since there is no "cmdKey" :( – FooBar Nov 10 '13 at 20:23
  • Hey Jeffman, why would you suddenly delete all your accounts on SE? I hope everythings fine! – Moritz Roessler Nov 12 '13 at 08:40
1

The event handler contains with some data, e, which tells you if there was some combination of keys made that might be useful. e.shiftKey and e.ctrlKey are booleans that tell you if those keys were held down when pressing them.

Keep in mind you would probably want to e.preventDefault() when allowing this kind of action, so that a user can press ctrl+a and not select everything on the page.