0

i interested in learn how to correctly add .bind code to object, then he changed. This object is not unic and have class selector insted of id, but it have a <div> wrapper:

<div id="GDI">
  <table class = "Tiberium">
  ...
    <tbody>
     <tr>...</tr>
     ...
     <tr>...</tr>
    </tbody>
  </table>
</div>

<div id="NOD">
  <table class = "Tiberium">
  ...
    <tbody>
     <tr>...</tr>
     ...
     <tr>...</tr>
    </tbody>
  </table>
</div>

The data changed in table with class "Tiberium" in <tbody> space (e.g. was added new row), i need simple alert then data changed in GDI table, but dont know how to do it.

Code that i tried:

$('.Tiberium').bind('DOMSubtreeModified', Alert);

Where Alert is function. This code capture changes in both tables, and i got alerts then one of them changed. So how i can track changes only in "Tiberium" table in GDI space?

p.s. i'v tried $('#NOD').bind('DOMSubtreeModified', Alert); but this code alert me 3 times in row, and it possible run every code in function 3 times. (i think it happend in case of this hierarchy).

Nick Nikolaev
  • 141
  • 1
  • 7

2 Answers2

2

The DOMSubTreeModified event is deprecated. A better alternative to this solution is to use the MutationObserver.

var toBeObserved = document.getElementsByClassName('Tiberium');

if('MutationObserver' in window) { // ensure browser support
    var observer = new MutationObserver(myEventHandler); // instantiate
    observer.observe(toBeObserved, { // start observing
        childList : true,
        subtree   : true
    });
}

Everytime the toBeObserved element is mutated, the myEventHandler function will be called. You can add your custom code within this function.

Community
  • 1
  • 1
JasonK
  • 5,214
  • 9
  • 33
  • 61
0

Could you please try following code:

$('.Tiberium').bind('DOMSubtreeModified', function(){
    //check the parent div's id
    if($(this).parent().attr("id") == "GDI")
        Alert //your alert function call
});
vijayP
  • 11,432
  • 5
  • 25
  • 40
  • tested in chrome console, have same problems if both tables get changes at the same time it count them all, so i recieve 2 alerts instead of 1. `$('.Tiberium')` gives me link on 2 tables: `[table.Tiberium, table.Tiberium]` `$('.Tiberium').parent().attr("id")` gives id of first space: `GDI` – Nick Nikolaev Nov 14 '16 at 10:07
  • yes...you will get count 2 for `[table.Tiberium, table.Tiberium]` but my point is that the `if` condition we have added will get matched only for single `div` and `Alert` will have to come only once in that case. – vijayP Nov 14 '16 at 10:16
  • strange, if i make this: `$($($('.Tiberium')[1]).children()[1]).bind('DOMSubtreeModified', function(){ alert('NOTICE'); });` script alert 3 times in row, but this is bind to `` ! Why it fires 3 times? – Nick Nikolaev Nov 20 '16 at 09:44