Mutation Observer

Demonstration of Mutation observer

HTML

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<h1>Mutation listener demo</h1>
<button id="para">Add Paragraph</button>
<button id="gist">Get gist</button>
<button id="fullscreen">Fullscreen</button>
<p>Check console for DOM modication messages</p>
<p>Interesting note about <a href="http://jsperf.com/dom-mutation-observer-vs-mutation-events/8">mutation performance</a></p>
<p>Note: fullscreen doesn't work within an iFrame.</p>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>

JavaScript

mutationsAllowed = false;
//Only supported in firefox or chrome/safari, respectively.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
    console.log(mutations, observer);
    console.log(mutationsAllowed);
});

observer.observe(document, {
    subtree: true,
    attributes: true,
    childList: true
});

//Directly trigger a basic DOM mutation.
$('button#para').click(function(){
mutationsAllowed = true;
    $('body').append('<div> dynamic paragraph </div>');
    mutationsAllowed = false;
});

//Trigger a DOM mutation as part of a data get.
var gistURL = 'https://gist.githubusercontent.com/javajosh/4a6853aa6f0e7443b299/raw/1c7469b4d0ac6769ba7d0f9689c28082855bd9cd/gistfile1.json';
$('button#gist').click(function(){
    $.getJSON(gistURL, function(data) {
        data.forEach(function(obj){
            var items = [];
            $.each(obj, function(key, val) {
                items.push('<li id="' + key + '">' + val + '</li>');
            });
            $('<ul/>', {
                'class': 'my-new-list',
                html: items.join('')
            }).appendTo('body');
        });
    });
});

//https://github.com/sindresorhus/screenfull.js
$('#fullscreen').click(function(){
    if (document.fullscreenEnabled) {
        console.log('fullscreen requested');
        requestFullscreen(document.documentElement);
    }
});

document.fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.documentElement.webkitRequestFullScreen;

function requestFullscreen(element) {
    if (element.requestFullscreen) {
        element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
    } else if (element.webkitRequestFullScreen) {
        element.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
    }
}