How to get text cursor position after keypress event happened?

Sebastian Zartner picture Sebastian Zartner · May 2, 2016 · Viewed 14.7k times · Source

I am writing a syntax highlighter. The highlighter should update the highlighting immediately while entering text and navigating with the arrow keys.

The problem I'm facing is that when the 'keypress' event is fired, you still get the old position of the text cursor via window.getSelection().

Example:

In the example, place the caret before the word 'foo', then press (the Right Arrow key).

Within the console of your favorite DevTool you'll see the following:

keydown 0
keypress 0
keyup 1

That 0 besides keypress is obviously the old caret position. If you hold down a bit longer, you'll get something like this:

keydown 0
keypress 0
keydown 1
keypress 1
keydown 1
keypress 1
keydown 2
keypress 2
keyup 2

What I want to get is the new caret position like I would get it for 'keyup' or 'input'. Though 'keyup' is fired too late (I want to highlight the syntax while the key is pressed down) and 'input' is only fired when there is actually some input (but doesn't produce any input).

Is there an event that is fired after the caret position has changed and not only on input? Or do I have to calculate the position of the text cursor and if so, how? (I assume this can get quite complicated when the text wraps and you press (the Down Arrow key).)

Answer

ConnorsFan picture ConnorsFan · Oct 23, 2016

You can use setTimeout to process the keydown event asynchronously:

function handleKeyEvent(evt) {
    setTimeout(function () {
        console.log(evt.type, window.getSelection().getRangeAt(0).startOffset);
    }, 0);
}

var div = document.querySelector("div");
div.addEventListener("keydown", handleKeyEvent);
<div contenteditable="true">This is some text</div>

That method addresses the key processing problem. In your example, you also have a span element inside of the div, which alters the position value returned by

window.getSelection().getRangeAt(0).startOffset