Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver fails to observe textarea

I'm trying to add custom undo operations to a textarea element by using a MutationObserver object. I've looked on MDN for how to use this object, and as far as I know I seem to be using it correctly. However, none of the mutations are registering - I want to observe whenever the text in the textarea changes.

function initObserver() {
    var editorObserver = new MutationObserver(function(mutations) {
        console.log("MUTATION");

        mutations.forEach(function(mutation){
            console.log(mutation.type);
        });
    });

    var editorObserverConfig = { characterData: true };

    var editor = document.querySelector("#editor");

    editorObserver.observe(editor, editorObserverConfig);
}

initObserver();

What might be wrong with this code?

like image 218
NmdMystery Avatar asked Nov 13 '15 01:11

NmdMystery


2 Answers

Simplest approach would be to use oninput event

var editor = document.querySelector("#editor");
editor.oninput = function(e) {
  // do stuff
}
like image 111
guest271314 Avatar answered Sep 24 '22 19:09

guest271314


To answer your question as to what is wrong with that code mutation observers observe changes to the DOM. Value changes to a form element are not reflected by the DOM so would not trigger the mutation observer.

So in short there is nothing wrong with that code. But you aren't changing the DOM when you enter text into a text area.

like image 43
AtheistP3ace Avatar answered Sep 23 '22 19:09

AtheistP3ace