Saving/restoring caret position in a contentEditable div

Ok, this is a tough one…

I have a contentEditable element, and am using setTimeout() to call a function which changes the innerHTML of the div. Problem is that changing innerHTML moves the caret to the end of the text.

I need to keep the caret pos so the user can keep typing. I tried storing the caret pos with

And then later restoring it with - which is IE only, but it doesn’t work because the content of the div gets changed between calls, and the behavior is undefined (it basically selects everything)

Here’s what I have so far:

It’s used for spell checking text as you type it, try typing something in there, and watch it get spell checked.

Only works in IE right now, sorry Firefox folks :slight_smile:

Ok, I managed to work around it, here’s the solution if anyone’s interested:

Store the selection x, y:

clickx = cursorPos.getBoundingClientRect().left;
clicky = cursorPos.getBoundingClientRect().top; 

Restore the selection:

cursorPos = document.body.createTextRange();
cursorPos.moveToPoint(clickx, clicky);;