0

I want to create an event when the content of a div changes, the event is called..

change = function(oldval,newval){
    if (oldval != newval){
        return true;
    }
    return false;
}

I want this function to be called everytime the content of a div changes ..Any idea how i can achieve this ?

Manish Basdeo
  • 6,139
  • 22
  • 68
  • 102
  • Possible duplicate of [DOM Mutation event in JQuery or vanilla Javascript](http://stackoverflow.com/questions/7692730/dom-mutation-event-in-jquery-or-vanilla-javascript). Some of the answers there link to jQuery plugins that might solve your problem. Handling DOM mutation events is often trickier than it looks, though. – Frédéric Hamidi Feb 05 '12 at 08:43

2 Answers2

1

I want this function to be called everytime the content of an element changes

If the content of an element equals to the value of form inputs:

One line code:

$(':input', $('#divId')).change(function(){alert('changed');});

Or the delegate option for dynamic added elements (still one line... (; ):

$('#divId').on('change', ':input', function(){ alert('changed');});

docs:

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Why does this get upvoted? It won't raise the event when the content of the `
    ` changes, but when the value of a form control inside of it changes, which is not the same thing at all. And the last sentence is not even complete...
    – Frédéric Hamidi Feb 05 '12 at 09:12
  • @FrédéricHamidi. I'm sure this is what the qustion owner meant. **"content of an element changes"** – gdoron Feb 05 '12 at 09:22
  • Indeed, `content of a div changes`, not `value of form controls inside a div changes`. I'm afraid the questioner is looking for the former (mutation events), not the latter... – Frédéric Hamidi Feb 05 '12 at 09:26
  • @FrédéricHamidi. We shall wait for the question owner response... Anyway it's a good answer, the question isn't clear enough. – gdoron Feb 05 '12 at 09:28
  • 1
    @FrédéricHamidi. "content of an element changes" not "content of a div changes"! – gdoron Feb 05 '12 at 10:38
  • Both sentences are actually present in the question... not that it makes a difference anyway. – Frédéric Hamidi Feb 05 '12 at 12:12
1

If you arent planning on supporting IE you can use DOMNodeInserted and DOMNodeRemoved to check if elements are added or removed from your div.

$('#yourDiv').bind('DOMNodeInserted DOMNodeRemoved', function(event, oldvalue, newvalue) {
   if (oldval != newval){
        return true;
    }
    return false;
});

for IE support you can use

$(function() {
  var $div = $("#yourDiv");
  var content = $div.html();
  var look = setInterval(function() {
    var newcontent = $div.html();
    if (html != newcontent ) {
      change(content, newcontent); 
      content = newcontent;
    }
  },100);

  function change(oldval, newval() {
     if (oldval != newval){
        return true;
    }
    return false;
  }
});
Mouna Cheikhna
  • 38,870
  • 10
  • 48
  • 69