How do I keep the caret position when I update the innerHTML of the contenteditable div it is in?

Viewed 100

I am trying to make some code with a contenteditable div, so if you type some specific words, they change colour. I got this working thanks to some stack overflow (What else) but whenever I update the innerHTML of the element I am working with, it moves my caret (The blinky thing that you type with) To the start of the text. Is there a way I can preserve my caret position in this div?

const words = [
  "apple",
  "banana",
  "pear"
]

document.getElementById("colordiv").addEventListener("keypress", colorchange)

function colorchange() {
  var cont = document.getElementById("colordiv").innerHTML.split(" ");
  for (i = 0; i < cont.length; i++) {
    if (words.includes(cont[i])) {
      cont[i] = "<span style='color:blue'>" + cont[i];
      cont[i] = cont[i] + "</span>";
    }
    document.getElementById("colordiv").innerHTML = cont.join(" ");
  }
}
<div id="colordiv" contenteditable="true">
  This text can be edited by the user.
</div>

0 Answers
Related