views:

33

answers:

3

Hello,

Is there a way to Observe the Contents of a specific DIV, I want to call a function as soon as the contents of the DIV are Changed.

This can be a innerHTML replace, a page load.

Thanks

A: 

In this page, it says that DIVs should fire OnChange when their content is modified.

Observing a div for change is not an effective technique. Have you looked into getting the code that changes the DIV's content to trigger and event?

Alternatively you could set a timer that monitors changes in your div and triggers some event.

Am
-1 `onchange` is case-sensitive and it's not cross-browser
galambalazs
+1  A: 

You can check the contents of the element comparing to the previous value.

Retrieve the element to watch

var div = document.getElementById("w");

Create a watcher:

var w1 = { watch: null, prev: div.innerHTML };

Start the watcher. Each 100ms it will compare the previous value to the current value, if it's different it will update the value and trigger any actions.

function Watch(w, e)
{
    w.watch = setInterval(function() {
       if (e.innerHTML != w.prev)
       {
           w.prev = e.innerHTML;
           alert("changed");
       }
    }, 100);
}

Watch(w1, div);

See this example on jsFiddle.

BrunoLM
+2  A: 

In modern browsers you can use DOM mutation events like DOMSubtreeModified, DOMCharacterDataModified. In IE you've got onchange event which you can use. For all the other browsers you can set up a timer for checking if the content has been changed.

galambalazs