Detect change of textContent(value) of HTML table cell and apply animation on changed data

Viewed 302

I have just coded HTML Table using Javascript. And cell data of table is renewed every 2 seconds by API(some statistic number data), here is my code:

function dataRenew {
  for(var i = 0;i < fooArray.length; i++) {
    var id = fooArrayID[i];
    document.getElementById(id).textContent = fooArray[i].someStatisticNumber;
    // id is for each cell
  }
}
//....
setInterval(function () {
  dataRenew();
}, 2000);

This has worked well. but I want to add animations or some effects based on Data Change of Cell, just like:

When cell data is renewed as New Data by API, cell's color of background go fadeout and fadein again.

console.log('Look ma, no JavaScript!');
@-webkit-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-moz-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@-o-keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
@keyframes invalid {
  from { background-color: red; }
  to { background-color: inherit; }
}
.invalid {
  -webkit-animation: invalid 1s infinite; /* Safari 4+ */
  -moz-animation:    invalid 1s infinite; /* Fx 5+ */
  -o-animation:      invalid 1s infinite; /* Opera 12+ */
  animation:         invalid 1s infinite; /* IE 10+ */
}
td {
  padding: 1em;
}
<table>
  <tr>
    <td>true</td>
    <td class="invalid">false</td>
    <td>true</td>
    <td>true</td>
  </tr>
</table>

This example isn't renewing data but the animation is just what I want, anyway this is just an effect example, I just want to know how to apply the effect when data of cell changes.

Vanilla JS is preferred but jQuery is ok

2 Answers

You are probably looking for MutationObserver which provides the ability to watch for changes being made to the DOM tree. You have to set subtree: true if you would like to observer innerHTML changes.

thx to Jax-p

this is just my code

td {
  transition: all 0.5s;
}

var config = {
  childList: true,
};

$(".fooID").each(function () { // fooID is td's id value
  var target = this;
  var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
      // console.log(mutation.target);
      // console.log(mutation.removedNodes[0].data); // mutation.removedNodes[0].data = old value
      // console.log(mutation.target.textContent); // mutation.target.textContent = new value
      if (
        parseFloat(mutation.target.textContent) <
        parseFloat(mutation.removedNodes[0].data)
      )
        mutation.target.style.color = "blue";
      else mutation.target.style.color = "red";
      setTimeout(function () {
        mutation.target.style.color = "black";
      }, 300);
    });
  });

Related