domwebkitmutation-events

is there an alternative to DOMAttrModified that will work in webkit


I need to leverage this DOM event. IE has onpropertychange, which does what I need it to do also. Webkit doesn't seem to support this event, however. Is there an alternative I could use?


Solution

  • Although Chrome does not dispatch DOMAttrModified events, the more lightweighted mutation observers are supported since 2011 and these work for attribute changes, too.

    Here is an example for the document body:

    var element = document.body, bubbles = false;
    
    var observer = new WebKitMutationObserver(function (mutations) {
      mutations.forEach(attrModified);
    });
    observer.observe(element, { attributes: true, subtree: bubbles });
    
    function attrModified(mutation) {
      var name = mutation.attributeName,
        newValue = mutation.target.getAttribute(name),
        oldValue = mutation.oldValue;
    
      console.log(name, newValue, oldValue);
    }
    

    For a simple attribute change, the console.log statement would print:

    <body color="black">
    <script type="text/html">
    document.body.setAttribute("color", "red");
    </script>
    </body>
    

    Console:

    > color red black