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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With