skip to Main Content

I saw this code here:

myCombobox.addEventListener('keydown', function(event) {
  if (event.key === 'Escape') {
    myCombobox.close();
    event.stopPropagation();
  }
});

My education and experience tells me that the code should be comparing a constant.

myCombobox.addEventListener(MouseEvents.KEYDOWN, function(event) {
  if (event.key === KeyboardConstants.ESCAPE) {
    myCombobox.close();
    event.stopPropagation();
  }
});

Is there a class or object in JavaScript that has a list of all the keys and keyboard events on it?

Other languages do this for very obvious specific reasons, to prevent typos, which prevent errors and non-functioning code.

Does Javascript love errors or do these classes exist and I couldn’t find them?

I tried to suggest this to TC39 and they said it’s not a language feature. Where do I suggest this feature?

2

Answers


  1. If you really want to make this suggestion, you can make it here:
    https://github.com/w3c/uievents-code/issues/

    You can refer to this list whenever you need:
    https://www.w3.org/TR/uievents-code/#key-alphanumeric-writing-system

    There’s all the current KeyboardEvent codes described there.

    Login or Signup to reply.
  2. Nothing stopping you from creating your own list of event.key string values…

    For a start:

    const KeyboardConstants = Object.freeze( 
      { BACKSPACE  : 'Backspace'
      , TAB        : 'Tab'
      , ENTER      : 'Enter'
      , ESCAPE     : 'Escape'
      , SPACE      : 'Space'
      , PAGE_UP    : 'PageUp'
      , PAGE_DOWN  : 'PageDownq'
      , END        : 'End'
      , HOME       : 'Home'
      , LEFT       : 'ArrowLeft'
      , UP         : 'ArrowUp'
      , RIGHT      : 'ArrowRight'
      , DOWN       : 'ArrowDown'
      , INSERT     : 'Insert'
      , DELETE     : 'Delete'
      // ...
      });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search