Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Contenteditable div: save and restore caret position when is positioned in empty new line

I need to save and restore the caret position as the user types in a contenteditable div (the html written is edited and re-inserted with each key pressed).

I've read and succesfully used this solution by Tim Down to a similar question: https://stackoverflow.com/a/13950376/2086428.

The problem occurs when the caret is positioned in an empty line, it will be restored to the previous non-empty line (try it here, add a new line and save / restore the cursor).

In the comments section of the solution proposed one user had the same problem, the author of the solution hinted to convert the <br>s into characters.

How can I do this? Are there any simpler solutions?

PS: I can't use rangy for this project.

like image 218
Ted R Avatar asked Feb 17 '14 15:02

Ted R


1 Answers

From this answer:

The solution is to make sure, that every "br" tag is followed by a newline character (\n).

This won't hurt the HTML content in any visible way, but now all HTML breaks are translated to plain text line breaks as soon as range.toString() is being called.

<br>\n

Working example here: http://jsfiddle.net/gEhjZ/95/

For comparison, example, which has problem (without \n after "br"): http://jsfiddle.net/gEhjZ/94/

like image 52
dima.rus Avatar answered Sep 24 '22 23:09

dima.rus