Observe Node And Attribute Changes In The Document - jQuery Mutation Observe

File Size: 59.1 KB
Views Total: 423
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Observe Node And Attribute Changes In The Document - jQuery Mutation Observe

Mutation Observe is a jQuery plugin which invokes specified callback functions when attributes and/or nodes have been changed in the DOM.

Powered by the Mutation​Observer Web API that provides the ability to watch for changes being made to the DOM tree.

See Also:

How to use it:

1. To get started, include both jQuery library and the Mutation Observe plugin on the web page.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="jquery-mutation-observe.js"></script>

2. Execute a callback when a specific attribute has been changed.

  • data.oldValue: Old value
  • data.newValue: New value
$('.element')
  .observeAttribute({
    'attributes': 'class',
    'callback': function(data){
      log('attribute:class has been changed from ['+data.oldValue+'] to ['+data.newValue+'] on self');
    }
})

3. Execute a callback when a node has been added or removed from the DOM.

$('.element')
  .observeNode({
    'selector': '> .child',
    'callback': function(data) {
      var tag = escapeHtml($(data.node).prop('outerHTML'));
      if (data.type=='add') {
        log('node has been added to a child element directly under self element. <br>tag: ' + tag);
      } else if (data.type=='remove') {
        log('node has been removed from a child element directly under self element. <br>tag:' + tag);
      }
    }
})

This awesome jQuery plugin is developed by takitakit. For more Advanced Usages, please check the demo page or visit the official website.