How to capture ALT+N on keypress in JavaScript
Try :
window.addEventListener('keydown', function(e) {
if (e.altKey == true && e.keyCode == 78)
console.log('Alt + N');
});
Using keypress
event doesn't work for me for Alt+N and for any combination with Alt for that matter. Some combinations are working with Ctrl and some aren't.
However, when I listen for keydown
and keyup
events, I am able to log these events. So, I guess you could listen for keydown
event on Alt and if there is a keydown
event for N before Alt generates keyup
, you have successfully detected a Alt+N combo.
I am not sure about why this happens though.
EDIT
According to Mozilla documentation,
The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys.
Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.
As for why some shortcuts work in Chrome, while some do not, Mozilla says
Chrome does not fire the keypress event for known keyboard shortcuts. Which keyboard shortcuts are known depends on the user's system. Use the keydown event to implement keyboard shortcuts.