Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOMNodeInserted/Removed event polyfills (or similar events)

I need a way to listen for changes for when a node's children are removed or added. I made an autoscrolling plugin that keeps an element scrolled to the bottom as new items are added. The event I'm listening to is DOMNodeInserted and DOMNodeRemoved.

I was looking for polyfills for DOMNodeInserted and DOMNodeRemoved. Looking around I wasn't able to find any that already existed. The event is not supported in all browsers and is currently deprecated.I have a simple (likely naive) polyfill I wrote quickly but I doubt it works (well).

I know these events are deprecated, but is there a better way to listen for element children changes?

(function() {
    var works = false;
    var $test = document.createElement("div");
    var $testchild = document.createElement("a");

    $test.addEventListener("DOMNodeInserted", function() {
        works = true;
    }, false);

    $test.appendChild($testchild);

    if(!works) {
        var nodeproto = Node.prototype;
        var nativeAppend = nodeproto.appendChild;
        var nativeRemove = nodeproto.removeChild;

        nodeproto.appendChild = function() {
            nativeAppend.apply(this, arguments);
            this.fireEvent("DOMNodeInserted");
        };

        nodeproto.removeChild = function() {
            nativeRemove.apply(this, arguments);
            this.fireEvent("DOMNodeRemoved");
        };
    }
})();
like image 943
megawac Avatar asked Nov 13 '13 20:11

megawac


People also ask

What is a mutation event?

The MutationEvent interface provides event properties that are specific to modifications to the Document Object Model (DOM) hierarchy and nodes.

What is DOMNodeInserted?

DOMNodeInserted : Fires when a node has been added as a child of another node. DOMNodeInsertedIntoDocument : Fires when a node is being inserted into a document.

What is mutating Dom?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.


1 Answers

I ended up writing a reasonably compliant polyfill for MutationObserver using interval checks of a cloned childList (similar to what @plalx mentioned in his comments) instead of falling back on the MutationEvents. MutationEvents will be more performant for most scenarios as any poll vs interrupt implementations but compatibility sucks

Simple auto scrolling example using my shim

like image 139
megawac Avatar answered Nov 15 '22 10:11

megawac