Search code examples
javascripthtmlcursor

Is there a simple way to prevent the cursor from moving in a div contenteditable at all, even if JavaScript is used to add text?


I had the following code:

document.getElementById("myDiv").addEventListener("keydown", function (e){
  if (e.keyCode == 8) {
    this.innerHTML += "⠀".repeat(4);
    e.preventDefault();
  }
  //moves cursor
});
<div id="myDiv" contenteditable="true">Enter text.</div>
Iv'e seen similar questions, but the answers that Iv'e seen are insufficient for a div contenteditable, and many of them don't work at all.
how do I make sure that the cursor doesn't get moved automatically?


Solution

  • Try this.

    const el = document.getElementById("myDiv");
    const sel = window.getSelection();
    const offset = sel.getRangeAt(0).startOffset;
    
    el.innerHTML += 'Text needed to be added'; // perform operations here
    
    const nRange = document.createRange();
    nRange.setStart(el.childNodes[0], offset);
    nRange.collapse(true);
    
    sel.removeAllRanges();
    sel.addRange(nRange);
    

    I haven't checked in all browsers. You'll have to perform some additional steps to have browser compatibility but this is the gist of it.

    Demo here: https://jsbin.com/xesitepima/edit?html,js,output

    Partially taken from: https://stackoverflow.com/a/6249440/2492924