Ethan
Ethan

Reputation: 3808

How to capture ALT+N on keypress in JavaScript

I have some simple code which logs the pressed key code, like this:

window.addEventListener('keypress', function(e) {
  console.log(e.keyCode);
})

It seems to work for Alt + pretty much every other on my keyboard. Except for Alt + N. It seems to not be registering the event at all! Just N (without the Alt) seems to work, and so do other combinations like Ctrl + N. When I type Alt + N nothing else happens, so it's not been reserved by the system as far as I know. I am using Chrome on a Mac.

Is this just something wrong with my computer or does it happen for others too? If it does happen for others, why does it do this and are there ways to detect it?

Upvotes: 8

Views: 6828

Answers (2)

Mayank K Rastogi
Mayank K Rastogi

Reputation: 604

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.

Upvotes: 3

Ashraf
Ashraf

Reputation: 2632

Try :

window.addEventListener('keydown', function(e) {
  if (e.altKey == true && e.keyCode == 78)
    console.log('Alt + N'); 
});

Upvotes: 7

Related Questions