Marius
Marius

Reputation: 4016

contenteditable div loses selection when another input focuses

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:

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:

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?

Upvotes: 5

Views: 7296

Answers (1)

Tim Down
Tim Down

Reputation: 324507

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.

Upvotes: 11

Related Questions