$.change jQuery MutationObserver lib

A smallish example of a very trivial jQuery listener for changes to HTML structure, as detected by a MutationObserver.

by NOVUSIDEA

HTML

<button rel="#a">edit</button>
<pre id="a" class="watched">a</pre>
<br>
<button rel="#b">edit</button>
<pre id="b" class="watched">b</pre>

CSS

.watched {
    border: 2px solid #ccc;
}

pre {
    display: inline-block;
}

JavaScript

// a minimal jQuery library for reacting to innerHTML changes
(function($) {
    $.fn.change = function(cb, e) {
        e = e || {
            subtree: true,
            childList: true,
            characterData: true
        };
        $(this).each(function() {
            function callback(changes) {
                cb.call(node, changes, this);
            }
            var node = this;
            (new MutationObserver(callback)).observe(node, e);
        });
    };
})(jQuery);

$('.watched').change(function(changes, observer) {
    this.style.borderColor = randomCol();
    console.log('element ' + this.id, changes, observer);
})

function randomCol() {
    var rrggbb = Math.floor(Math.random() * 0x1000000).toString(16);
    return '#' + ('00000' + rrggbb).slice(-6);
}

$('button[rel]').click(function() {
    var $b = $(this),
        $el = $($b.attr('rel'));
    $el.html(randomCol());
});