14

I have this code:

$(document).bind('keydown', 'ctrl+1', function () {
    alert('You found the hotkey ctrl+1!');
});

But if I click on either the Ctrl or the 1 key, this code seems to fire. I only want this code to fire when both keys are pressed.

What am I missing?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
leora
  • 188,729
  • 360
  • 878
  • 1,366

10 Answers10

17

As you can see in the documentation, the second argument to the bind function is eventData, which is

An object containing data that will be passed to the event handler.

This is used to access variables from outside the inner function which you use as a handler, to avoid the problem with accessing a mutable variables from closure.

If you want to filter the keys that trigger the action just handle it inside of the function.

$(document).bind("keydown", function(ev){ // notice the function argument
    if(ev.ctrlKey && ev.keyCode == 49){ // 49 being the keyCode for "1"
        alert("Foo!");
    }
});
Dropout
  • 13,653
  • 10
  • 56
  • 109
  • Wouldn't this also handle Ctrl+Alt+1, as well as Ctrl+Shift+1? – Roland Illig Feb 18 '17 at 10:10
  • @RolandIllig yes, it would get triggered as it checks only if Ctrl&&1 is pressed. As long as the key combination doesn't get *picked up* by a higher layer which would prevent it getting to your code it would get triggered. For example if we would be expecting Ctrl+L and you'd press Ctrl+Alt+L the combination would be handled by Windows first as a locking action and wouldn't be passed on to the browser if I'm not mistaken. I'm sure you get my point here. Same may happen on JS level where one action simply prevents the event being handled by another handler - ev.stopPropagation() – Dropout Feb 20 '17 at 11:53
3

You can use the keydown function of jQuery directly and check for the keys pressed.

$('body').keydown(function (e){
    if (e.ctrlKey && e.keyCode == 49)
        alert("Ctrl+1 pressed");
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

Use:

document.body.addEventListener('keypress', function (event) {
    var key = event.which || event.keyCode;
    if(key.ctrlKey && key == 49) {
        alert("Ctrl+1 pressed);
    }
}

This should help. You add an event listener to the body of your HTML code and listen for which key was pressed.

$(document).ready(function () {
    document.body.addEventListener('keypress', function (event) {
        var key = event.which || event.keyCode;
        if (key.ctrlKey || key == 49) {
            alert("Ctrl+1 pressed");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html lang="en">
    <head>
    </head>

    <body>
        <p>empty page</p>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheOddCoder
  • 161
  • 1
  • 12
3

The keyword "+" becomes of a CSS selector. It is not a listener to keyboard events (keydown, keypress, and keyup).

In this context, you don’t need a CSS selector to detect key. This magic correspond to an event, and for this reason there is a function that receives the event ...function (event) or function(e). That parameter contains everything that you need.

Now the event identifies the key by property "which" or property "keyCode". Here is a sort of complex, because which and keycode, depends on the browser support.

For now, maybe must check the keydown event on the jQuery page, observe the line 41, and the result when you press a key, specially the keycode and the which attributes.

Finally, the target is detecting the Ctrl key simultaneously with another key. It is important to know it is a special key, and which number must be replaced by ctrlKey and evaluate the number by the property which or keyCode.

jQuery link to keydown and example that make you know what key number (which or keycode) are you press is here.

Your code finally will look like this:

$(document).bind('keydown', function (e) {
    if((e.crtlKey && (e.which == 49)) || (e.crtlKey && (e.which == 97))) {
        alert('You found the hotkey ctrl+1!');
    }
});

The number 49 in the code corresponding to the number ="1" in the alphabetical keyboard part.

The number 97 corresponds to the number ="1" in the numerical keyboard part.

Sk.
  • 460
  • 7
  • 15
2

Directly use the jQuery event instead of bind. Use the ctrlKey property of the event object to know if Ctrl was pressed.

$(document).keydown("1", function(e){
    if(e.ctrlKey)
        alert("Ctrl+1 pressed");
});

It wasn't tested, but I guess it should work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Teja
  • 1,236
  • 12
  • 27
2

You need to check for a keydown event as well as if the Ctrl key was pressed

$(document).keydown('1', function(e) {
    if (e.ctrlKey) {
        alert('Ctrl 1 was pressed.');
    }
});

Just to clarify on your question, you missed checking the ctrl event.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
codemirror
  • 3,164
  • 29
  • 42
1

Make use of jQuery hotKeys. It will make your life much easier. You will be able to do something like:

$(document).bind('keydown', 'ctrl+1', function () {
    alert('You found the hotkey ctrl+1!');
});

Another library is Mouse trap. It lets you do things like:

Mousetrap.bind('command+shift+k', function(e) {
    highlight([6, 7, 8, 9]);
    return false;
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Medard
  • 1,039
  • 10
  • 17
0

You are doing it wrong. The key down event fires at the moment when you press a key and it does not care if you are pressing another key. Please use the keyup event.

$(document).bind('keyup', 'ctrl+1', function () {
    alert('You found the hotkey ctrl+1!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anil Sharma
  • 128
  • 4
  • 19
0

Try this:

$(document).keypress("1",function(e) {
  if(e.ctrlKey)
    alert("You found the hotkey ctrl+1!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<p>Press CTRL+1 to show alert.</p>

More info here.

Community
  • 1
  • 1
Samuel Tulach
  • 1,319
  • 13
  • 38
-2

This function will be called on each key press, but I have checked for keycodes in a condition. We can implement the required functionality in the "if condition". The condition will execute only when Ctrl key and 1 is pressed.

$(document).on('keydown', 'body', function(event) {

    if (event.ctrlKey && event.keyCode == 49) {

        alert("Ctrl+1 pressed");
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131