Search code examples
javascriptkeypresswysiwygtext-editor

How to detect actual characters only with JS key-events (for text-editor)


I am working on a WYSIWYG-like editor for equations (in combination with plain text). Since implementing the functionalities (for equations) that I'd like to have won't work using the existing frameworks (contentEditable or document.designMode), I am now building an editor from scratch. (so far it has worked out good, I've successfully implemented most functionalities of a normal editor)

I've been using the keydown event to detect user input while in "edit-mode" (that is, when the user has clicked on the editor-area, also displaying the cursor), but the problem with that is, that when clicking "alt" or "strg" or other keys that aren't actual characters, they'll also get displayed in my editor.

Now, what I've tried is to ignore those keys by using if-statements, but there are 2 issues I see with that: 1. It may influence performance, when too many keys have to be ignored 2. I can never be sure, if there doesn't exist some exotic key, perhaps on a Mac or so, which I didn't ignore

I have also tried to use the keypress event instead, which worked mostly fine, but still displayed "Enter" and "Delete", so who knows what others keys it may display too. Also, it is labelled as "deprecated".

Are there any better ways of doing that, or will I just have to make a big list of keys to ignore?


Solution

  • A simple (but limited) approach would be to check if the keydown event's keyCode is between 65 (code for key 'a') and 90 (code for 'z').

    If you need more than just letters though, another solution would be to check the event's key and its length. For actual characters, the key simply holds that character (so length 1). For Ctrl, Shift, etc., key will hold the full name of the key, e.g. "Control", "Shift", etc.

    So, if a key is an actual character, the key property will have a length of 1.

    document.onkeydown = function(e) {
      var keycode = e.keyCode;
      if(e.key.length == 1) {
        document.querySelector("#editor").innerHTML += e.key;
      }
    }
    <p id="editor"></p>