Change cursor position in the contenteditable div after changing innerHTML

Viewed 6960

I have a simple contenteditable div with some text in it. On onkeyup event i want to replace whole content (innerHTML) of the div based on regex.

For example,

HTML:

some text, more text and $even more text

Function in which i plan to get all text with $ ($even in example above) and wrap it in span tag:

div.onkeypress = function() { 
     div.innerHTML.replace(/(some_regexp)/, "<span class='class'>$1</span>"); 
}; 

The problem is after such replacement cursor jumps to the start of the div. I want it to stay where it was before.

I imagine i have to save coordinates of the cursor before change and then somehow using them set cursor back but how can i do it? :)

I tried saving range object but after editing i believe it points to nowhere.

Thanks!

3 Answers

I took this from another forum. It solved my problem.

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

Store the selection x, y:

Code:

cursorPos=document.selection.createRange().duplicate();
clickx = cursorPos.getBoundingClientRect().left; 
clicky = cursorPos.getBoundingClientRect().top;

Restore the selection:

Code:

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

You can see it working here:

http://www.tachyon-labs.com/sharpspell/

Related