I'm new to jQuery and I've some problem of redundant execution of an event handler. Here is my code:
$(document).bind('keydown', 'ctrl+c', function(){
console.log("Something is wrong!!!");
});
I'm not pressing, Ctrl+C at all, but my console is printing the message as many times as I'm pressing any key. What's the flaw here? Thanks in advance, for any assistance.
You're binding the event to ANY keydown
. You want to use the keydown
event, but then check to make sure that your specified keys are the ones being pressed. e.ctrlKey
will check for Ctrl, and you can use e.which
to compare the other key, which in this case would be C
Here's a full example
$(document).bind('keydown', function(e) {
console.log('some key pressed');
if (String.fromCharCode(e.which).toLowerCase() == "c" && e.ctrlKey) {
alert('ctrl+C pressed');
}
});