Nick Nikolaev
Nick Nikolaev

Reputation: 141

jQuery .bind on change some object with .class

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).

Upvotes: 0

Views: 430

Answers (2)

JasonK
JasonK

Reputation: 5294

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.

Upvotes: 2

vijayP
vijayP

Reputation: 11512

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
});

Upvotes: 0

Related Questions