R.Bianchi
R.Bianchi

Reputation: 27

alert() when div content changes using mutationobserver

i would like make a script (javascript) that check if the content of a div changes (by ajax, so without refresh the page) and then shows an alert() message. I think i can use mutation observer but i can't understand how to do it... The script must re-check the page every 60 second. Thanks for the help.

//now create our observer and get our target element
var observer = new MutationObserver(fnHandler),
        elTarget = document.querySelector(".w-portfolio-table-body"),
        objConfig = {
            childList: true,
            subtree : true,
            attributes: true, 
            characterData : true
        };

//then actually do some observing
observer.observe(elTarget, objConfig);

function fnHandler () {
    alert("DETECTED_VARIATION");
}

NOTE: This code is for a chrome extension, so i can't use onchange event :(

Upvotes: 0

Views: 4694

Answers (1)

Christophe
Christophe

Reputation: 28124

First, you should not use your event handler to insert a new element (h2 here), or else you'll end up with an infinite loop.

Second, you need to bind your handler to the observer.

For example:

function fnHandler () {
  alert("DETECTED_VARIATION");
}
var observer = new MutationObserver(fnHandler);

Demo: http://jsfiddle.net/drLrd9w5/1/

Upvotes: 4

Related Questions