Detect DOM Changes In A Container Using Mutation Observer - waitforChild.js

File Size: 10.3 KB
Views Total: 886
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Detect DOM Changes In A Container Using Mutation Observer - waitforChild.js

The MutationObserver web API is a powerful tool for tracking changes on the DOM. It's built into browsers, and we can use it with jQuery, also. 

waitforChild.js is a tiny jQuery plugin that uses the Mutation Observer API to monitor for DOM changes on a specific container. When it detects an appended of a new child, it then fires an event.

See Also:

How to use it:

1. Download the plugin and include the jquery.waitforChild.js script after jQuery.

<script src="/path/to/cdn/jquery.slim.min.js"></script>
<script src="/path/to/jquery.waitforChild.js"></script>

2. Now let's append some elements to a specified container.

<ul id="example">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

3. Now let's append some elements to a specified container.

$('#example').append('<li class="fouth">Item 4</li>');
$('#example').append('<li class="fifth">Item 5</li>');
$('#example').append('<li class="sixth">Item 6</li>');
...

4. Invoke the function and then find all newly appended elements.

$('#example').waitforChild({
  onFound: function(child) {
    // do something
  },
});

5. Determine whether to apply the onFound function only on the first matching child. Default: false.

$('#example').waitforChild({
  onFound: function(child) {
    // do something
  },
  once: true,
});

6. Or apply the onFound function only on the specific element.

$('#example').waitforChild({
  onFound: function(child) {
    // do something
  },
  querySelector: 'li.fouth',
});

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