Search code examples
javascripthtmlkeypress

Javascript: Get what character and where from key press


I'm trying to get the exact input change (what character and where) which comes from key press to an input field in HTML5 but I can't figure out how to do it "nicely".

My findings so far:

Event oninput(event) is too high-level, it basically says: "something" has changes. I don't know where and what exactly. Comparison of the original and current values sounds heavy for a big string. Event onkeypress(event) is too low-level it does not care about where event.which goes into the input field.

Is there a way to get both what character user typed and where exactly?


Solution

  • It is a broad question, but I'll try to answer anyways. You can listen to onkeydown event and know what key has been pressed.

    window.onkeydown = function(event) {
          alert(String.fromCharCode(event.keyCode) + " was pressed");
       }
    };
    

    After that you can get the position of where the key has been pressed.

    var cursorPosition = $('#myTextarea').prop("selectionStart");
    

    What you want to do with this basic information is up to you! You can build a little more intelligent code on top of this. Good luck!