In my page I have added function in jQuery
which runs every 5 seconds. This function:
- Collects current records in a array
currentRecords
- Makes an
AJAX
call and gets the new records in an arraynewRecords
- If the
newRecords
list contains a new record, this is added to the page.
The above logic is working right:
HTML:
<div class="pending-calls">
<div class="call-record" id="id1">Record 1</div>
<div class="call-record" id="id2">Record 2</div>
<div class="call-record" id="id3">Record 3</div>
</div>
jQuery:
(function worker() {
//Get current records
var currentRecords = [];
$('.call-record').each(function () {
currentRecords.push($(this).prop('id'););
});
$.ajax({
url: '#',
dataType: "json",
type: "POST",
success: function (data) {
//Save records to an array and find the new record. If you find a new one, prepend it 'newRow' to the page.
$('.pending-calls').prepend(newRow);
//e.g <div class="call-record" id="id4">Record 4</div>
},
complete: function () {
setTimeout(worker, 5000);
}
});
})();
However, when a new record is found and it is added to the page, on the next loop the $('.call-record')..
doesn’t catch it and as a result this new record <div class="call-record" id="id4">Record 4</div>
is added endlessly in the page.
2
Answers
I found a walk around to my problem. I placed the array
currentRecords
outside of the function, so when the page is loaded it is filled once with the current records. After theajax
call, if I found a new record I added to the list.The issue is that your initial selector doesn’t capture new elements added later. To solve this, use the
.on()
method to detect and add newly inserted call-record elements tocurrentRecords
. This is the modifiedjs
.Hope this works for you.
PS: Please Note that Using
DOMNodeInserted
may lead to performance problems when there are frequent additions of numerous elements to theDOM
. Event handling might be excessive if real-time response toDOM
changes isn’t necessary