tnw
tnw

Reputation: 13877

Detecting multiple key press in javascript

I'm attempting to detect a number of key combinations in javascript. I need to detect Ctrl + Left, Ctrl + Right, Right, and Left.

So far I'm just trying to detect when Ctrl is pressed. Here's what I have (JSFiddle link):

var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;

    printKeys();
});

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

    printKeys();
});

function printKeys() {
    var html = '';
    for (var i in keys) {
        html += '<p>i: ' + i + '</p>'
        if (!keys.hasOwnProperty(i)) continue;
        if ($.inArray(17, keys) > -1) 
            html += '<p>ctrl was pressed, return val: ' + $.inArray(17, keys) + '</p>'
    }
    $('#out').html(html);
}

I guess I don't really understand how JQuery's inArray is supposed to work because when I press any key, it just returns -1. The if statement also evaluates to true while I only want it to do that when Ctrl is pressed. How can I fix this so that my if statement properly detects Ctrl being pressed? I'll be able to figure the rest out once I get that working properly.

EDIT: Changed if-statement to evaluate inArray returning > -1

Upvotes: 3

Views: 4256

Answers (5)

ORION
ORION

Reputation: 2401

In javascript you would need to capture the value of the window.event.ctrlKey to detect if the control key is being pressed. Here is an example of a function that would use to block pasting from the clipboard into a field using the ctrl+v keyboard shortcut:

    function BlockControlV() {
        var keyPressed = window.event.keyCode;
        var ctrlPressed = window.event.ctrlKey;
        if (ctrlPressed && keyPressed == 86) {

            var ClipBoardData = window.clipboardData.getData('Text')
            ClipBoardData = trim(ClipBoardData)

            if (ClipBoardData != '') {
                if (isNaN(ClipBoardData) == true) {
                    window.event.keyCode = 0;
                }
            }
            else {
                window.event.keyCode = 0;
            }
        }
    } 

Though not exactly relevant to what you're trying to do, you should be able to figure out what direction you should be heading.

Upvotes: 3

Karlen Kishmiryan
Karlen Kishmiryan

Reputation: 7522

You can detect it easily using the returned event object. This object also contains information about all control keys:

  • ctrlKey - does the Control key was pressed?
  • shiftKey - does the Shift key was pressed?
  • altKey - does the if Alt key was pressed?

All of these properties are boolean values (true, if button was pressed, otherwise` false).

Here is the demosntration of aforementioned properties in JSFiddle.

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 15112

Firstly, You're missing braces {} for the else case.

js Fiddle DEMO

if (i == 17) {
    html += '<p>ctrl</p>';
} else {}

Run the Demo & watch the text "ctrl" show up while you click Ctrl key.

e.ctrlKey is the easiest way to detect the Ctrl key click.

To detect Ctrl + left Demo here

$(document).keydown(function(e){
    if(e.keyCode == 37 && e.ctrlKey)
        alert("Control + Left Clicked"); 
});

Upvotes: 0

stinkycheeseman
stinkycheeseman

Reputation: 45737

First, keys is not an array- it is an object. So instead of the 2 separate if blocks in your function, you can write simply:

if (keys.hasOwnProperty(i)) {
  ...
}

Secondly, jQuery appends a very convenient property to event objects: ctrlKey.

In your keydown event handler, wrap the call to printKeys in an if statement:

if (e.ctrlKey) {
  printKeys();
}

Finally, to detect whether ctrl + (any other key), simply check whether the which property on the event corresponds to one of the keyCodes you are looking for

Upvotes: 1

David Thomas
David Thomas

Reputation: 253308

The simplest way to find out whether the ctrl is pressed, is to test the event object for the ctrlKey property:

$(document).keypress(function(e){
    console.log(e.which, e.ctrlKey);
});

JS Fiddle demo.

I would have provided a more relevant demo, but I have no idea what that demo's meant to achieve.

Upvotes: 1

Related Questions