2

I'm having difficulties in retaining the caret position in a content editable div after I update it through javascript.

I have a div with a contenteditable attribute.

<div id="form", contenteditable="true">
</div>

Let's say the user typed "Bacon is so good! I want more" I update the html inside the div where I wrapped certain words with a span. From the html above, it would turn into this:

<div id="form", contenteditable="true">
   Bacon is so <span>good</span>! I want more!
</div>

I do this by updating the html using jQuery...

$('#form').html(...here I put the updated html...)

However after this, the caret (cursor) returns to the start of the div. I want to keep the caret in the same position as before I update the div in order for the user to continue typing without any hitch.

Currently, I have the following code:

I first save the caret position prior to updating the div.

if(window.getSelection) {
    window.savedRange = window.getSelection().getRangeAt(0);
} else if(document.selection) { 
   window.savedRange = document.selection.createRange();
} 

And then I try to return the caret position by

$('#form').get(0).focus();
if (window.savedRange != null) {
    if (window.getSelection) {

        var s = window.getSelection();

        if (s.rangeCount > 0) 
            s.removeAllRanges();

        s.addRange(window.savedRange);
    } else if (document.createRange) {
        window.getSelection().addRange(window.savedRange);
    } else if (document.selection) {
        window.savedRange.select();
    }
}

I need to retain the caret because this should all happen while the user is typing. The code above didn't do anything. It still returns to the start of the div.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
carmina
  • 307
  • 2
  • 10
  • 2
    http://stackoverflow.com/a/17694760/96100 – Tim Down Sep 23 '13 at 17:13
  • 1
    You can also read [how the selection is being restored in CKEditor](http://stackoverflow.com/questions/16835365/set-cursor-to-specific-position-in-ckeditor/16859577#16859577). – Reinmar Sep 23 '13 at 18:31

0 Answers0