0

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?
Sapphire_Brick
  • 1,560
  • 12
  • 26
  • So, you want to prevent the tab to gain the focus in another element on the page? If that's the case, just prevent the default action by adding the line `e.preventDefault();` inside the `if` block. – Teemu Oct 25 '19 at 18:46
  • @Teemu-callmewhateveryouwant you're right, I did forget to put the `e.preventDefault`, but that's not the point. the point is that I want a way to prevent the cursor from moving when JavaScript is used to add text. The tab is just an example, but I want to retain the cursor position automatically. – Sapphire_Brick Oct 25 '19 at 19:13
  • OK, but at first you've to improve the question. Add examples of what you have tried, so that we're not going to waste our time by creating and suggesting you something you know doesn't work. And the current example ... a div element shows the tab character as the backslash and t, HTML can't contain escape sequence characters like `\t` or `\n`, (a pre element would accept those, though). – Teemu Oct 25 '19 at 20:02

1 Answers1

1

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

Vivek
  • 4,786
  • 2
  • 18
  • 27