#StackBounty: #javascript #html #dom #contenteditable #cursor-position ContentEditable div – set cursor position after updating inner h…

Bounty: 50

I have a spell check solution that uses a content editable div and inserts span tags around words that are misspelled. Every time the inner html of the div is updated, the cursor moves to the beginning of the div.

I know I can move the cursor to the end of the div if the user adds new words to the end of the sentence (code below).

Old Text: This is a spell checker|

New Text: This is a spell checker soluuution|

var range = document.createRange();
range.selectNodeContents(element[0]);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);

However, I am unable to retain the cursor position if the user adds words in the middle of a sentence.

Old Text: This is a spell checker

New Text: This is a new spell checker|

In the above case, the cursor goes to the end of the div when it should be after “new”.

How do I retain the cursor position? Since I am updating the html and adding nodes, saving the range before the update and adding it to the selection object isn’t working.

Thanks in advance.


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.