1

How do I stop the cursor changing location when innerHTML is edited by javascript?
I am currently making a little code editor project where I want text highlighting, but to do that I must edit the innerHTML / DOM element to add a span into it. But when that happens it changes location to start of text.

var c = document.getElementById("c");
var t = setInterval(function(){
 c.innerHTML = $("#c").text().split("lol").join("<span class='hi1'>lol</span>");
},1);
[contenteditable] {
    border: 1px solid gray;
}

.hi1 {
  color: rgb(51, 153, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable id="c">
    write "l o l" without spaces. Then continue to write and try to change location with arrow keys / mouse
</div>
  • I'd change the interval to an event listener, look into http://stackoverflow.com/questions/3972014/get-caret-position-in-contenteditable-div and also cache the old `$("#c").text()` before changing it to avoid unnecessary rewrites – Isaac Oct 31 '16 at 00:55
  • On the answer from that page is correct, but it does not support multilines –  Oct 31 '16 at 00:57
  • yea but it might be a good place to start. I've attempted to do stuff like this in the past, it's never easy. I think I resorted to an opaque textarea on top of a div, and reformatted all the text styling to try my best to get it to match... best of luck :S – Isaac Oct 31 '16 at 01:01
  • Thanks @Isaac, well for sure I cannot use textarea ;( sadly i am currently stuck with editable –  Oct 31 '16 at 01:08

0 Answers0