Search code examples
jqueryonchangeparagraph

Detect paragraph element change with JQuery


Is it possible to detect if the content of a paragraph has been changed in JQuery ?

I tried the below code.

<p id="test">Text</p>
<button id="submit1">change</button>

-

$(document).on("click", "#submit1", function () {
    var d = new Date();
    var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    $("#test").text(time);
});       
$(document).on("change", "#test", function () {
    alert("Paragraph changed");
});

JSFiddle : http://jsfiddle.net/nnbqye55/

I guess I am missing something obvious.


Solution

  • 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});
    });