Search code examples
javascriptmutation-observers

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?


Solution

  • Simplest approach would be to use oninput event

    var editor = document.querySelector("#editor");
    editor.oninput = function(e) {
      // do stuff
    }