SentinelJS Demo

by tnhu

HTML

<button onclick="addDiv();">Add another DIV</button>
<div class="my-div"></div>

CSS

.my-div {
  animation-duration: .5s;
  animation-name: slidein;
}

@keyframes slidein {
  from {
    margin-left: 100%;
    width: 300%; 
  }

  to {
    margin-left: 0%;
    width: 100%;
  }
}

JavaScript

// https://gist.github.com/sheodox/a2c7f8c7021964842827

function filteredNewNodeCallback(root, selector, callback) {
    var obs, i;

    if (!root || !selector || !callback) {
        return;
    }

    function filterAndCallback(node) {
        var matches = [], childMatches;
        if (node.matches(selector)){
            matches.push(node);
        }
        childMatches = node.querySelectorAll(selector);
        if (childMatches.length !== 0) {
            matches = matches.concat([].slice.call(childMatches))
        }
        matches.map(callback);
    }

    obs = new MutationObserver(function(mutations){
        mutations.forEach(function(mutation){
            for(i = 0; i < mutation.addedNodes.length; i++) {
                if (mutation.addedNodes[i].nodeType === 1) {
                    filterAndCallback(mutation.addedNodes[i]);
                }
            }
        })
    });
    obs.observe(root, {childList: true, subtree: true});
}

/* test stuff */

//make new tweets on twitter red
filteredNewNodeCallback(document.querySelector('#timeline'), '.js-stream-item', function(tweet){
    tweet.style.background = 'red';
});

var target = document.body

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    console.log({ mutation })
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
    	console.log('Added', newNodes)
    }
  });    
});

// Configuration of the observer:
var config = { 
	attributes: true, 
	childList: true, 
	characterData: true 
};
 
// Pass in the target node, as well as the observer options
observer.observe(target, config);

// add a new div to the DOM
function addDiv() {
  var newEl = document.createElement('div');
  newEl.className = 'my-div';
  newEl.textContent = 'New div'
  document.body.appendChild(newEl);
}

window.addDiv = addDiv