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 ?

1

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

6 Comments

Why does this get upvoted? It won't raise the event when the content of the <div> 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éricHamidi. I'm sure this is what the qustion owner meant. "content of an element changes"
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éricHamidi. We shall wait for the question owner response... Anyway it's a good answer, the question isn't clear enough.
@FrédéricHamidi. "content of an element changes" not "content of a div changes"!
|
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;
  }
});

1 Comment

where do the oldvalue, newvalue values come from ?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.