JQuery warning if table rows change (Fiddle inside)

So what I'm trying to do, a warning is executed every time the top row of the table changes. The problem is that I update the HTML every 10 seconds, so I cannot figure out how to β€œlisten” to the changes.

http://jsfiddle.net/kYZYU/1/

<table id="theTable">
<th>Id</th>
<th>Name</th>
<th>Score</th>
    <tr>
        <td>1</td>
        <td>James</td>
        <td>50</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Peter</td>
        <td>25</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Sally</td>
        <td>10</td>
    </tr>
</table>


$("#theTable").on("change", function() {
    alert("This person took the lead");
});


//Goal: An alert every time someone new takes the lead. The problem is, at this point - the table HTML is regenerated every 10 seconds (it will be better solution soon), so it kind of hard to "listen for changes". 

What I think: 1. At the page load, look at the first row of the table and save the value of the user ID, the next time the HTML is restored, do the comparison?

+4
source share
1 answer

First you need to bind a custom event to a table:

// table listening to an "update" custom event
$('#leaderboard-spot').on('update', function(){
    alert('Table updated, launching kill space goats sequence now.')
});

When your ajax request is successful and your table is updated, fire a custom event on the table:

function loadLeaderboard() {
    var competitionId = $("body").attr("data-competitionId");
    var url = "leaderboard_api.php?competitionId=" + competitionId;
    $.get(url, function (data) {
        $("#leaderboard-spot").html(data);
        // manually triggering an update
        $("#leaderboard-spot").trigger('update');
    });
}
+7

All Articles