javascriptkeydownonkeydown

KeyboardEvent: detect that a key has a printed representation


In my React/Javascript app, I am listening for KeyboardEvents. The documentation for the key property is quite clear on how to get the pressed key value:

Its value is determined as follows:

  • If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.
  • If the pressed key is a Space key, the returned value is a single space
  • If the pressed key is a control or special character, the returned value is one of the pre-defined key values.

I want to test that the pressed key has a printed representation or is a Space. i.e. it is NOT one of the pre-defined key values.

I could not find a hasPrintedRepresentation property. Should I write my own hasPrintedRepresentation() that tests and excludes each one of those 400-or-so pre-defined key values before returning true? I could not find a library that already does this grunt work. Did I miss something? Thank you!


Solution

  • You could use the key property of the KeyboardEvent object to get the pressed key value.

    You could use the Object.hasOwn() method in JavaScript to check if the key property of the KeyboardEvent object has a printed representation or is a Space. The Object.hasOwn() method returns true if the specified object has the indicated property as its own property. If the property is inherited, or does not exist, the method returns false.

    Here's an example of how you could use the Object.hasOwn() method to test if the pressed key has a printed representation or is a Space:

    function hasPrintedRepresentation(event) {
      const key = event.key;
      return Object.hasOwn(key, 'length') && key.length === 1 || key === ' ';
    }