I tried to implement an infinite scroll, or a “load on scroll” if you want, on a html table.
The data is stored in the db and I access it with my code behind.
I implemented it from an example on msdn like this:
JS
$(document).ready(function () {
function lastRowFunc() {
$('#divDataLoader').html('<img src="images/ajax-Loader.gif">');
//send a query to server side to present new content
$.ajax({
type: "POST",
url: "updates.aspx/GetRows",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data != "") {
$('.divLoadedData:last').before(data.d);
}
$('#divDataLoader').empty();
}
})
};
//When scroll down, the scroller is at the bottom with the function below and fire the lastRowFunc function
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
lastRowFunc();
}
});
// Call to fill the first items
lastRowFunc();
});
Code behind is not so interesting, it’s just returning the data (20 rows each time) from the DB in this format (one for each row):
<tr><td>Cell 1 data</td><td>Cell 2 data</td><td>Cell 3 data</td></tr>
ASPX
<table>
<thead>
<tr><th>Header 1</th><th>Header 2</th><th>Header 3</th></tr>
</thead>
<tbody>
<div class="divLoadedData">
</div>
</tbody>
</table>
<div id="divDataLoader">
</div>
The problem is, when data is loaded and inserted to the page (even on the first load), the table headers are going after the data. I do see all the rows I loaded but the table headers are at the bottom of the page (after the 20 rows I loaded).
I tried few variations to insert the loaded data:
$('.divLoadedData:last').before(data.d);
or
$('.divLoadedData:last').append(data.d);
or
$('.divLoadedData:last').after(data.d);
but none of them worked.
Would be happy to hear any suggestions about how to implement it correctly with a html table and make it work.
It could be because the HTML is invalid:
tbodyis only supposed to containtr. Why not append the rows directly to thetr, like this?HTML
JS
This JSBin compares this way and the way you are currently trying. Looking at your way in Chrome’s DOM inspector, it appears that Chrome is moving the
divto before thetable.I added a border to the table in the JSBin to show that the
divis getting moved outside of it.