Search code examples
javascriptkeyboard-shortcutskeypress

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?


Solution

  • Try :

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