Is it possible to detect if the content of a paragraph has been changed in JQuery ?
I tried the below code.
Text
The approved answer didn't work for me so here is my revised and working example for anyone looking.
function getNode(){
//Store the test paragraph node
var test = $('#test');
if(!test){
// The node we need may not exist yet
// Wait 500ms and try again
window.setTimeout(getNode, 500);
return;
}
//Function to change the paragraph
var changeParagraph = function () {
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
test.text(time);
};
//Bind the paragraph changing event
$('#submit1').on('click', changeParagraph);
//Observe the paragraph
this.observer = new MutationObserver(changeParagraph);
this.observer.observe(test, {characterData: true, childList: true});
});
//Delay calling our function until page loads
setTimeout(function() {
getNode();
}, 5000);
change
events won't fire on the paragraph. What you need are known as Mutation Observers. Here is the relevant MDN documentation. They have pretty good browser penetration; for older IEs, you can probably use the deprecated Mutation Events, though those are known to be performance killers, so be very careful. I'll rewrite your example using Mutation Observers; you can also check out a jsFiddle demo:
$(function(){
//Store the test paragraph node
var test = $('#test');
//Function to change the paragraph
var changeParagraph = function () {
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
test.text(time);
};
//Bind the paragraph changing event
$('#submit1').on('click', changeParagraph);
//Observe the paragraph
this.observer = new MutationObserver( function(mutations) {
alert('Paragraph changed!')
}.bind(this));
this.observer.observe(test.get(0), {characterData: true, childList: true});
});
You can use 'DOMSubtreeModified' to check the dom changes on html tag elements. See the support for this event across browsers.
http://jsfiddle.net/nnbqye55/7/
$(document).on("DOMSubtreeModified", "#test", function () {
alert("Paragraph changed");
});
On change you have to trigger change event like below
$(document).on("click", "#submit1", function () {
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
$("#test").text(time).trigger("change");
});
$(document).on("change", "#test", function () {
alert("Paragraph changed");
});
JS Fiddle
You can attach the change()
event only to <input>, <select>
and <textarea>
element and detect their value change. Not on other elements.
Check here
You can use the code from here http://quiiver.appspot.com/method_observer_for_jquery and use it like
$('#test').bind('text' // the method's name used to change the text
, function(){
alert("Paragraph changed");
})
DEMO However, it works only for modifications done through jQuery.