Hemanth.HM

A Computer Polyglot, CLI + WEB ♥'r.

DOM Mutation Observers

| Comments

M4 API MutationObservers can be used to observe mutations to the tree of nodes.

It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.

All you get with it is:

1
2
3
4
var observer = new MutationObserver(callback); // Get the changes.
observer.observe(target, options); // Observer the desired node with options.
observer.disconnect(); // Stop observing.
observer.takeRecords(); // Empty the record queue and returns what was in there.

List of options:

img

Check out a sample DEMO I made for fun, which load random images from different sources ;)

The code looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var matrix = document.querySelector("#imgs");
    var imgServ = ["http://lorempizza.com/i/380/240",
                   "http://lorempixel.com/380/240/"
                  ];

    var observer = new MutationObserver(function(mutations){
        mutations.forEach(function(mutation){
                var size = matrix.childElementCount;
                matrix.children[size -1 ].src = imgServ[Math.floor(imgServ.length * Math.random())]+"#"+ Math.random().toString(36).substring(7);
        });
    });

    observer.observe(matrix,{childList: true});

    setInterval(function(){
            matrix.appendChild(document.createElement('img')
            )},1000
    );

Don't miss to read the spec

Happy hacking, till next time ;)

Comments