5

I have a problem with contenteditable div. When i want to execute a simple command (like bold or italic) on it, i do the following:

  • memorize the div (since it will lose focus after i click on bold button)
  • on button click, i refocus the div and execute the bold command
  • everything works

Now the problem occurs when i try to do something more difficult. For instance, i want to show a custom dialog with an input field:

  • memorize the div
  • on button click, a dialog is shown (everything is still ok)
  • user focuses an input field on that dialog (and that's where everything breaks)

The problem with this is that as soon as an input element is focused, not only that my contenteditable div loses focus - it also loses the selection and moves the cursor to the beginning as soon as i refocus it.

So my question is: how do i prevent a contenteditable div to lose its selection after i focus on another input element?

Marius
  • 3,976
  • 5
  • 37
  • 52

1 Answers1

11

If the input and contenteditable element are within the same document, you won't be able to prevent the selection in the contenteditable element from being destroyed. However, what you can do is save the selection before the input box receives focus and restore the selection after the dialog is dismissed.

Here is some simple example code:

https://stackoverflow.com/a/3316483/96100

And here's a fuller example:

https://stackoverflow.com/a/4690057/96100

If you place either the input or contenteditable element within a separate iframe, most browsers (although not IE) will preserve the original selection.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks, Tim. How didn't i find this myself ... Works like a charm! – Marius Oct 08 '12 at 10:19
  • Are you sure you can't prevent this? Google Hangouts appears to manage preventing the selection from being destroyed (from what I can observe in Google Chrome Developer Tools). – Trevor Sep 17 '13 at 23:19
  • @threed: That's because the hangout box is in a separate iframe. Perhaps I should have mentioned that. – Tim Down Sep 18 '13 at 08:51
  • 3
    I managed to get this working without using a separate iframe. When I click on a – Trevor Sep 18 '13 at 19:08
  • @TimDown does the iframe way preserve selection in IE9+ ? – medBouzid May 06 '16 at 18:21