I try to implement hotkey functionality using jQuery.
The goal is to call functions when Ctrl + 'some letter' is pressed.
This works when using keypress()
, but keypress()
doesn't work in Chrome and IE.
keydown()
works in major browsers, but in this case the problem is - prevention of default browser behavior, i.e. New Window is opened when Ctrl + N is used.
My code is:
var ctrlDown = false;
jQuery(document).keydown(function (e) {
e.preventDefault();
if (e.ctrlKey) {
ctrlDown = true;
if (ctrlDown && e.which == 13) {
alert('ctrl + enter');
}
else if (ctrlDown && e.which == 78) {
alert('Ctrl + N');
}
} else {
ctrlDown = false;
}
});
I also tried stopPropagation()
, but it didn't help. What can be done in order to prevent browser's default behavior?