1

The cursor gets moved to the beginning instead of being set to last type position when the change event is fired. I am using content editable div using angular js.

plunker

http://plnkr.co/edit/FFaWNZmgk00Etubtjgg8?p=preview

Why does the cursor position move to beginning?

dmullings
  • 7,070
  • 5
  • 28
  • 28
DevÁsith
  • 1,072
  • 12
  • 38

3 Answers3

3

I know this is an old question but, as I've been searching my whole working day to find a solution to this issue, I'd like to share this solution to people who might still looking for a working answer :

var el, el2, range, sel;

el = element[0];
range = document.createRange();
sel = window.getSelection();
if (el.childNodes.length > 0) {
  el2 = el.childNodes[el.childNodes.length - 1];
  range.setStartAfter(el2);
} else {
  range.setStartAfter(el);
}
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);

I got this code originally from akatov/angular-contenteditable directive, "moveCaretToEndOnChange" method. and this worked for me.

ssuperczynski
  • 3,190
  • 3
  • 44
  • 61
Behzad
  • 425
  • 4
  • 10
0

I would assume Angular is rewriting the innerHTML property of the editable element, thus destroying and recreating all of the DOM tree within it, which results in the caret resetting to the start. See these answers for potential solutions:

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

In my case I was using the same reference of array for changing the innerHTML as was used on the DOM (two way binding). Hence the dom re-rendered and thus the cursor moved to the beginning.

The Solution was to make a deep copy of the array using JSON.parse(JSON.stringify(a)); where a is the array that stores the words that are contenteditable and then do the change
let filetexts =JSON.parse(JSON.stringify(this.filetexts)); // updating the current text filetexts[alternativesIndex].Alternatives[0].Words[wordIndex].Word = html; let data = { Text: JSON.stringify(filetexts) }; this.fileService.changeFileText(data, this.file.fileId).subscribe(res => { });