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 whic开发者_运维百科h 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).
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.
How about this:
($.fn.watchChanges = function(cb){
$(this).each(function(i, e){
$(e).data("original_content", $(e).html());
window.content_changes = window.content_changes ? window.content_changes : [];
window.content_changes.push({"element": e, "callback": cb});
});
return $(this);
})(jQuery);
setInterval(function(){
if(window.content_changes)
{
$.each(window.content_changes, function(i, e) {
if($(e.element).data("original_content") != $(e.element).html())
{
e.callback.apply($(e.element));
$(e.element).data("original_content", $(e.element).html())
}
});
}
}, 500);
Usage:
$('.foo').watchChanges(function(){
$('.bar').html("something's different about you, foo!");
});
This may be a "duh" kind of answer, but honestly I think your best bet is to simply modify your "change the DIV" function so that it calls another function:
function addInputToDiv(newInput) {
div1.append(newInput);
takeSomeActionToDiv2InResponse();
}
This isn't as cool as using crazy events like DOMSubtreeModified ... but it will work in all browsers.
精彩评论