Listen to specific changes in contenteditable?

Warning: do not duplicate existing questions, read

I know that I may have an event to listen for changes in the contenteditable element.

What I would like to know is what changes .

For instance:

  • inserted "This sentence". at position X.
  • removed from position X to Y.
  • X to Y with <strong>

Is it possible? ( other than using diff, I mean )


The reason for this is the creation of a WYSIWYG editor for languages ​​other than HTML, such as Markdown.

Therefore, I would like to apply the changes to the Markdown source (instead of moving from HTML to Markdown).

+6
source share
4 answers

You might be able to do something with MutationObserver (returning to D OM Mutation events in older browsers, although IE <= 8 does not support any), but I suspect that it will still be hard work to achieve what you want.

Here is a simple example of using MutationObservers:

http://jsfiddle.net/timdown/4n2Gz/

+4
source

Sorry, but there’s no way to know what changes are made without distinguishing between the original content and the changed when the changes occur.

+3
source

The API you are looking for does not exist because the DOM nodes do not retain their previous states.

The data / events you want to return are not built-in implementations in any browser that I encounter, and I try my best to think of a data type that could handle all of these cases in general terms. maybe something like this:

 function getChanges() { /* do stuff here to analyse changes */ var change = { changeType : 'contentAdded', changeStart : 50, /* beginning character */ changeContent : 'This is a sentence' } return change; } 

Since you are trying to get custom events / data, you probably need a special module or micro library. In any case, in order to look at the changes of something, you need to somehow be aware of what has changed, which can only be done by comparing what it was with what it is now.

0
source

You are looking for it

 var strong=document.createElement("strong"); var range=window.getSelection().toString().getRangeAt(0); range.surroundContents(strong); 

it was for the third part

You just need to choose what you want to use, using real user interaction.

If you want to do it dynamically

 var range=document.createRange(); range.setStart(parentNode[textNode],index to start[X]) range.setEnd(parentNode[textNode],index to end[Y]) range.surroundContents(strong); 

For the second part

 range.deleteContents() 

Part 1 can be done using a simple iteration

var textnode = // node of the element you are working with

 textnode.splitText(offset) 

offset-position, relative to which the text is split node [here == X] Two child nodes were created from the parent editable element

Now use a simple insertBefore () for the parent editable Node element.

hope you find it useful

-1
source

Source: https://habr.com/ru/post/950998/


All Articles