2

I'm trying to inject <span> elements into the text a user is typing into a contenteditable <div>. Input events (DOMCharacterDataModified) periodically trigger requests to a service that identifies certain entities in the text, and I'd like to update it accordingly. For example,

<div id="editor" contenteditable="true">
    The New York Times is an American newspaper based 
    in New York City with worldwide influence and 
    readership.
</div>

becomes

<div id="editor" contenteditable="true">
    The <span class="name">New York Times</span> is an 
    American newspaper based in <span class="loc">New 
    York City</span> with worldwide influence and 
    readership.
</div>

Is there any way I can inject <span> elements without replacing the <div>'s content, thus preserving the user's text cursor position?

sam
  • 1,406
  • 2
  • 15
  • 25
  • [DOMCharacterDataModified is depreacted](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events). take a look to [How to change contenteditable input character, on keypress](https://stackoverflow.com/questions/39485516/how-to-change-contenteditable-input-character-on-keypress) – gaetanoM Mar 16 '18 at 14:28
  • Are you suggesting `keydown`? I'm aware of the deprecation, but thought that `input` would be the [way to go](https://stackoverflow.com/questions/1391278/contenteditable-change-events?answertab=votes#tab-top). – sam Mar 16 '18 at 14:44
  • yes, the link (way to go) is the right one – gaetanoM Mar 16 '18 at 14:59

1 Answers1

-1

I don’t know if it will preserve the text cursor position, but a straightforward JavaScript replace() should work, regardless of if it’s inside something that’s contenteditable.

str.replace("New York Times", "<span>New York Times</span>")
Zoe Edwards
  • 12,999
  • 3
  • 24
  • 43
  • That doesn't preserve text cursor position, unfortunately. – sam Mar 16 '18 at 14:16
  • 1
    Try looking at https://stackoverflow.com/questions/16105482/get-current-cursor-position-in-a-textbox and possibly save the position first, then apply the span, then put the cursor back? – Zoe Edwards Mar 16 '18 at 14:18
  • I've tried hard with saving and restoring cursor position, but I haven't been able to come up with a bullet-proof solution – particularly with async service requests. – sam Mar 16 '18 at 14:40