Gav Gav - 1 month ago 11
HTML Question

Detect content change on refresh

I'm doing a refresh inside the page to update a div, I'm trying to catch when the content in the div is changed, I tried using "DOMSubtreeModified" but it just detected the refresh every time.

I'm grabbing info from a page (donations.php) that just contains a dollar amount etc: $20.00 it refreshes every 5 seconds to look for new content. It updates okay but I want to trigger an alert on change not every 5 seconds.

function loadlink(){
$.get("donations.php", function(data) {
$('#results').html(data);
});
}

loadlink();

setInterval(function(){
loadlink()
}, 5000);


is my current code, I'm trying to detect a complete change on #results

Its a donation tracker for stjudes charity and I want to trigger an alert on the change.

Answer

You can store the old value of data and do a check against it.

(function () {

    var dollarVal = "";

    function loadlink() {
        $.get("donations.php", function (data) {
            $('#results').html(data);

            if (dollarVal !== data) {
                // trigger alert
                alert("Value has changed!");
            }

            dollarVal = data;
        });
    }

    loadlink();

    setInterval(loadlink, 5000);

}) ();

If you don't want an alert on the first time load, then do:

if (dollarVal !== "" && dollarVal !== data)
Comments