Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a change in the contents of a HTML element?

I am using Ruby on Rails 3.1.0 and the jquery-rails gem. I would like to bind a jQuery event (maybe I could use the live functionality...) to a HTML div tag so that I can check its content changes and, if so (that is, if new code is added to the that div tag), to create a custom text in another HTML div tag.

That is, in my view file I have:

<div id="div_content_1"></div>

<div id="div_content_2"></div>

I would like to add\remove an "Hello!" text message inside the div with id="div_content_2" eachtime the div content with id="div_content_1" changes (in my case, when an HTML input field is added to that div tag - read the example that follows). For example (in the "add" case), when the div with id="div_content_1"changes like this

<div id="div_content_1">
  <!-- The following 'input' tag was just added -->
  <input ... />
</div>

I would like to make it to work so to have an output like the following in the div with id="div_content_2":

<div id="div_content_2">
  <p>
    Hello!
  </p>
</div>

How can I do that?

P.S.: I am implementing a form for which a user, after selecting some option (this event is intended to generate HTML input fields in the div with id="div_content_1" - I make that for my custom purposes...) can order those option on the same page (the div with id="div_content_2" is intended to make possible the sorting process that I planned).

like image 487
user502052 Avatar asked Oct 07 '11 17:10

user502052


1 Answers

How about:

$('#div_content_1').bind('DOMSubtreeModified', function() {
    $('#div_content_2').html('<p>Hello</p>');
});

Working example: JSFiddle

This method is better than the other two because it does not use polling. Instead, it uses the Observer pattern, which is much better. However, the downside is that this won't work in versions of Internet Explorer lower than 9.

like image 96
John Kurlak Avatar answered Sep 27 '22 19:09

John Kurlak