ContentEditable div replace innerHTML on the fly

Is there a way (other than the Rangy library) to change the contentEditable Div InnerHTML on the fly, like on a keyboard, without losing the cursor / focus position? I would like to use pure javascript code as much as possible.

eg:

<div id="divId" contentEditable="true" onkeyup="change(this)"></div> 

then javascript:

 function change(element) { element.innerHTML = element.innerHTML.replace(/.../, '...'); } 

Thanks.

+2
source share
2 answers

If you are replacing HTML, you will need some tools to save and restore your selection. Possible options:

  • Insert elements with identifiers at the beginning and end of the selection before replacing HTML, then return them by identifier and move the selection borders using these elements. This is the most reliable method, and this is what Rangy does.
  • Keep some character-based offset for the beginning and end of the selection before replacing the HTML and then re-creating the selection. This has all the problems in the general case, but it can be good enough, depending on your needs. I have posted SO functions to do this before , which are Rangy dependent, but you can easily strip Rangy stuff if you don't mind losing support for IE <9.
  • Save and restore selection borders by pixel coordinates. Browser support is not good for this and is not suitable if your HTML replacement changes layout.
+5
source

This does not use the keyup event, but maybe that will be enough? Please note that in relation to the body you, obviously, can focus only on a certain element.

 document.body.contentEditable='true'; document.designMode='on'; void 0; 
0
source

All Articles