Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery alert if table rows change (Fiddle inside)

Tags:

jquery

So what I'm trying to do, is execute an alert each time the top row of a table changes. Problem is, I regenerate the HTML every 10 seconds of so - so I can't figure out how to "listen" for 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's kind of hard to "listen for changes". 

What I'm thinking: 1. On page load, look at the first table row and save the value of the User Id , next time the HTML is regenerated, run a comparison?

like image 747
user2656127 Avatar asked Dec 13 '13 13:12

user2656127


1 Answers

You will need to bind a custom event to the table first:

// 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 and your table is updated, fire the 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');
    });
}
like image 65
kayen Avatar answered Oct 17 '22 16:10

kayen