2

I have a div that the contenteditable attribute is true,

<div tabindex="1" id="editor" contenteditable="true"></div>

I have another div that acts like a button

<div>Click Me</div>

The problem am having is that after typing inside the editor box, I selected some text and when I clicked on the "click me" div the editor box looses focus and thus removing the highlighted text.

I used in js to programmatically send the focus back

document.getElementById("editor").focus()

But after this the selected text is no more selected the cusor just moves to the beginning of the editor box.

How do I get the focus to make sure the initial selected text is selected again after the click me has been clicked

Nickolay
  • 31,095
  • 13
  • 107
  • 185
idevosm
  • 45
  • 4

1 Answers1

0

One solution is setting user-select: none on your button-like div. If the browsers you care about support it, it's the simplest (but as discussed in the comments here, someone reported problems with getting it to work in Safari...)

Otherwise you'll have to save and restore the selection using JS, the text range module of rangy.js is useful for that. Check out https://stackoverflow.com/a/57546051/1026 for a usage example; in your case you'll need to save the selection onblur and restore it after processing the click on the button-like div.

Nickolay
  • 31,095
  • 13
  • 107
  • 185