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.