Flo93atx
Flo93atx

Reputation: 123

addEventListener - detect changes in div-elements?

I want to detect changes in div-elements. I tried already the "addEventListener" with some types (e.g.: change, load).

Here is my example, but the event won't trigger:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div id='DivElement'>Test Div Text...</div>
        <button type="button" onclick="EditDivElement()">click me!</button>

        <script>
            function EditDivElement() {
                ClickCounter++;
                SelectedDiv.textContent="new text content: " + ClickCounter;
            }

            function OnDivEdit() {
                alert("success!");
            }

            var ClickCounter = 0;
            var SelectedDiv = document.querySelector("#DivElement");

            SelectedDiv.addEventListener("change", OnDivEdit);
        </script>
    </body>
</html>

(Edit: It's for a browser-addon and it should be used on other websites.)

Upvotes: 12

Views: 24222

Answers (1)

BrunoLM
BrunoLM

Reputation: 100331

You can use a MutationObserver.

From MDN:

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

Note: Deprecated

What I have done in the extensions I wrote was to listen on DOMNodeInserted.

div.addEventListener("DOMNodeInserted", function (e) {
    e.target // 
}, false);

Upvotes: 26

Related Questions