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
  • 5,957
  • 21
  • 67
  • 100
  • 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 is supporting Monica
  • 142,542
  • 55
  • 282
  • 355
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
  • 37,194
  • 10
  • 47
  • 68