9

I know getting / setting cursor position in a contentEditable is damn near impossible. I don't care about knowing this information. I need to be able to save current selection, modify innerHTML of the div, and then restore the selection.

I've bee experimenting with the answer provided at contenteditable selected text save and restore . It works after typing in the div, but not after programmatically modifying the innerHTML of the div. Instead, when I call restoreSelection, the caret simply goes to the beginning.

Any suggestions as to how to be able to save / restore selection on a contentEditable after modifying the innerHTML instead of typing would be much appreciated.

Community
  • 1
  • 1

1 Answers1

3

If you're doing some kind of string substitution on the existing innerHTML of your editable element, you may be able to use my Rangy library and its save/restore selection module. It uses invisible elements with particular IDs to mark the start and end boundaries of the selection, so if your innerHTML change does not include these elements then this will not work.

Another alternative is to do it based purely on character indices within the text nodes of the element. I've written a naive implementation here: https://stackoverflow.com/q/5596688/96100

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 1
    The Rangy library is out, because I replace the innerHTML of the div in question, so it'd encounter the same problem. I'll give the indices option a go...thanks. –  Nov 23 '11 at 21:27
  • I get an error on line 1051 of uncompressed/rangy-core.js when using your second solution. "node.childNodes is undefined" "if (offset < 0 || offset > (do...e.length : node.childNodes.length)) {" –  Nov 23 '11 at 21:36
  • @user1022241 Rangy stores the `id`s of the marker elements rather than references to the elements themselves so if you're replacing the `innerHTML` with a string substitution of the current HTML it could still work. Re. the problem with the second suggestion, do you have an example I can look at? – Tim Down Nov 24 '11 at 00:51
  • Nice, Rangy library works like a charm. One feature that would be nice with the save / restore module is a collapseToEnd or collapseToStart in case one has a need to destroy the invisible spans for any reason. I'd be happy to contribute the code, as I'm about to write that exact method... –  Nov 24 '11 at 06:48
  • @user1022241: Unless I'm misunderstanding, that's not too hard anyway: `var sel = rangy.getSelection(); sel.selectAllChildren(editableDiv); sel.collapseToStart();` – Tim Down Nov 24 '11 at 09:22
  • I'm trying to collapse a selection to the start _of the selection_ and to remove the invisible markers. I tried the above method and the caret goes to the end of the div. –  Nov 25 '11 at 17:32