I'm writing a keypress event which executes special functions for certain control characters, but inserts any printable character into a string.
this.handle_keypress = function(event) {
    let callback = this.control_function[event.key];
    if(callback) {
        callback.bind(this)(event);
    }
    else {
        this.myText += event.key;
    }
}
this.element.addEventListener('keypress', this.handle_keypress.bind(this));
But this will insert the text for unmapped control characters into my string (e.g. 'LeftArrow' or 'Backspace'). How can I tell which characters are printable characters and which are control characters?
Back in the day, I would use event.which or event.charCode, but these are marked as deprecated now.
I cannot use the input event, as far as I know, because I am not typing into a textarea or input field.
I'm running this in Firefox.
There's no immediately way to determine if event.key is a control character.
But given that:
You can make a code to decide between either or:
var letters = [];
elm.addEventListener("keydown", function(e) {
  if(e.key.length == 1 || (e.key.length > 1 && /[^a-zA-Z0-9]/.test(e.key))) {
    letters.push(e.key);
  } else if(e.key == "Spacebar") {
    letters.push(" ");
  }
}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With