Skip to content Skip to sidebar Skip to footer

How Do I Make A Mutationobserver Work More Then Once?

I using to a MutationObserver so I can have a div react to changes. When it changes the changes to displayed in the div directly under, however it only runs once. If I type somethi

Solution 1:

You're telling the observer to observe childList and characterData mutations on the input, but the input has no characterData itself. It is the Text nodes inside the input that have characterData mutations.

That leaves the childList. With it, your observer is only triggered when a node is added or removed from the input (when you type the first character, press enter or delete a line).

To fix it, tell the observer to look at the input's descendants by changing the config to:

{attributes:false, childList:false, subtree: true, characterData:true}

and remove the condition in the observer callback because all mutations will be characterData now. Actually you can just do this:

let observer= newMutationObserver(function(mutations){
    display.textContent=input.textContent;
}); 

since you don't care how many mutations occurred since last time, just the current value.

Post a Comment for "How Do I Make A Mutationobserver Work More Then Once?"