Thursday, March 31, 2016

Load table data on scroll with jQuery

When we are working with huge records we need to place the data from server side. If we want to work with client side it will definitely affect the performance.

That time we can go for 'Infinite scroll' concept. You can find lot of paid plugins for that and here I'm giving you a simple jQuery snippet to do the same (in paid plugins you may get lot of additional features).

$(document).ready(function() { 
var totalCount = 100;
var onLoadCount = 10;
var nextSetCount = onLoadCount + 10;
var i;
var rowCount = document.getElementById('myTable').rows.length;
 $('#container').on('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
if( nextSetCount <= totalCount ){
for( var i= nextSetCount - 10 ; i <= nextSetCount ; i++  ){
$('#myTable').append('<tr><td>Dynamic Cell'+i+'</td><td>Dynamic Cell'+i+' </td></tr>');
}
nextSetCount += 10;
}
else{
return false;
}
}
    })
});

Lets say we have 10 records already in our table and our table should grow while scrolling.I gave the maximum limit as 100. I have tested with 1 Lakh plus records and it was working like a charm.

You can find the complete runnable html file here:
https://drive.google.com/file/d/0B1kWshgszP-6WG1QaF84enFEUmc/view?usp=sharing