6

I am working on a chat and have chat-wrapper. Inside the chat-wrapper new spans are created with the messages. Like so:

<div id="chat-wrapper">
    <span>msg 1</span>
    <span>msg 2</span>
    <span>msg ...</span>    
</div>

Is there a way to watch if #chat-wrapper gives birth to new children?

Preferably jquery..

Brainmaniac
  • 2,203
  • 4
  • 29
  • 53

2 Answers2

7

Use Mutation Observer, the example is given below:

function addNew() {
  var targetNode = document.getElementById('chat-wrapper');
  targetNode.innerHTML += '<span> Message' + targetNode.querySelectorAll('span').length + '</span>';
}

window.onload = function() {

  var targetNode = document.getElementById('chat-wrapper');


  var config = {
    attributes: true,
    childList: true,
    subtree: true
  };

  var observer = new MutationObserver(callback);


  observer.observe(targetNode, config);
}



// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
  for (var mutation of mutationsList) {
    if (mutation.type == 'childList') {
      console.log('A child node has been added or removed.');
    } else if (mutation.type == 'attributes') {
      console.log('The ' + mutation.attributeName + ' attribute was modified.');
    }
  }
};
<div id="chat-wrapper">
</div>

<button onclick='addNew()'>Add New</button>
Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
0

You can make use of setInterval function in javascript. See below code, here you can check length of child span for every 2 sec and compare it with previously calculated child length.

$(function(){
   var child = $("#chat-wrapper span").length;
   setInterval(function(){
       var newChild = $("#chat-wrapper span").length;
       if(child < newChild ) {
          console.log("child added");
          child = newChild;
       }
   }, 2000);
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57