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?
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.
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).
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!");
}
});
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With