27

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:

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

var div = document.querySelector("div");
div.addEventListener("keydown", handleKeyEvent);
div.addEventListener("keypress", handleKeyEvent);
div.addEventListener("input", handleKeyEvent);
div.addEventListener("keyup", handleKeyEvent);
<div contenteditable="true">f<span class="highlight">oo</span></div>

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).)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
  • 1
    I think you will have another problem using the keypress event. Chrome doesn't seem to fire the event when pressing an arrow key (Firefox does). There is an old chromium bug in status WontFix describing this: https://bugs.chromium.org/p/chromium/issues/detail?id=2606 – Alex Oct 23 '16 at 12:25
  • Thank you for the hint! Right, the `keypress` event is not fired, but [it's obviously marked as obsolete](https://www.w3.org/TR/uievents/#legacy-keyboardevent-event-types), anyway. As I saw now, the specification states that people are advised to use the `beforeinput` event instead. And `keydown` is also fired continuously. Though all those events are fired too early. I've now [filed an issue on the UI Events spec.](https://github.com/w3c/uievents/issues/111) in the hope to get a proper event for this. – Sebastian Zartner Oct 23 '16 at 13:18
  • 1
    Cursor positions / selecting etc are still a pita to support on all browsers. It's been a while that i needed this but [rangy](https://github.com/timdown/rangy) is very solid with cursor related stuff.. – Geert-Jan Oct 26 '16 at 21:35

3 Answers3

22

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
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • 1
    Using `setTimeout()` this way looks rather a hack but it works. So, thanks for that! If nobody finds a nicer solution the next days, I'll accept your answer. I'm aware of the altering in the position value, I just provided some simplified code in my example. The range returned by `getRangeAt(0)` also provides the text node within the `startContainer` property, which the `startOffset` refers to, so that's not a problem. – Sebastian Zartner Oct 24 '16 at 06:42
  • 1
    Calling `setTimeout(fn, 0)` is a well-known technique for running code after the current call stack has completed. You can see these articles: [Why is setTimeout(fn, 0) sometimes useful?](http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful), [What does setTimeout with a 0ms delay do?](https://www.quora.com/What-does-setTimeout-with-a-0ms-delay-do), [Javascript tutorial](http://javascript.info/tutorial/events-and-timing-depth); and this [entertaining video](http://2014.jsconf.eu/speakers/philip-roberts-what-the-heck-is-the-event-loop-anyway.html). – ConnorsFan Oct 24 '16 at 21:22
  • It doesn't work in my case sorry. I'm using Firefox 94. Moving the cursor all to the left. And than press 1x right. The index still says 0, while the cursor is on index 1. – Melroy van den Berg Nov 05 '21 at 00:30
2

Here's a solution correcting the position using the 'keydown' event:

function handleKeyEvent(evt) {
  var caretPos = window.getSelection().getRangeAt(0).startOffset;

  if (evt.type === "keydown") {
    switch(evt.key) {
      case "ArrowRight":
        if (caretPos < evt.target.innerText.length - 1) {
          caretPos++;
        }
        break;

      case "ArrowLeft":
        if (caretPos > 0) {
          caretPos--;
        }
        break;

      case "ArrowUp":
      case "Home":
        caretPos = 0;
        break;

      case "ArrowDown":
      case "End":
        caretPos = evt.target.innerText.length;
        break;

      default:
        return;
    }
  }
  console.log(caretPos);
}

var div = document.querySelector("div");
div.addEventListener("keydown", handleKeyEvent);
div.addEventListener("input", handleKeyEvent);
<div contenteditable="true">f<span class="highlight">oo</span></div>

Unfortunately this solution as is has several flaws:

  • When inside a child element like the <span> in the example, it doesn't provide the correct startOffset nor the correct startContainer.
  • It cannot handle multiple lines.
  • It doesn't handle all navigation options. E.g. jumping word-wise via Ctrl+/ is not recognized.

And there are probably more issues I didn't think of. While it would be possible to handle all those issues, it makes the implementation very complex. So the simple setTimeout(..., 0) solution provided by ConnorsFan is definitely preferable until there is an event for caret position changes.

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
1

Someone just mentioned on my request for an event for caret position changes that there is also a selectionchange event, which is fired at the document everytime the selection has changed.

This then allows to get the correct cursor position by calling window.getSelection().

Example:

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

document.addEventListener("selectionchange", handleSelectionChange);
<div contenteditable="true">f<span class="highlight">oo</span></div>
Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132