Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery, why is this function being called when I only click one of the two keys?

Tags:

jquery

keydown

I have this code:

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

but if I click on EITHER Control or 1 key, this code seems to fire. I only want this code to fire when BOTH keys are pressed.

Can anyone clarify what I am missing?

like image 864
leora Avatar asked Feb 29 '16 13:02

leora


People also ask

How call jQuery function only once?

jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.

What is keypress event in jQuery?

The keypress() method triggers the keypress event, or attaches a function to run when a keypress event occurs. The keypress event is similar to the keydown event. The event occurs when a button is pressed down. However, the keypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC).


2 Answers

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!");
    }
});
like image 82
Dropout Avatar answered Oct 12 '22 11:10

Dropout


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");
});
like image 29
Shalinee SIngh Avatar answered Oct 12 '22 11:10

Shalinee SIngh