Back to the index of articles and examples

Infinite Scrolling DataTable

The challenge was to create a table that got records appended as you scrolled. The solution was to create a ScrollingDataTable with an initial number of records and then keep adding as you scrolled into 'empty' space. The first challenge was how to create that empty space. The size and position of the knob on the scroll bar is meant to correlate to the size and position of the portion being viewed. We need to really fill that 'empty' space with something, otherwise, the scrollbar would reach the bottom when there is really more rows available, and it would jump back as soon as those rows are added to represent the end is further away. So, the first task is to fill up that 'empty' space, which we do by creating a <tfoot> section:

We keep a reference to the single cell in that section because it is the height of that cell that will compensate for the missing records. We calculate it on the renderEvent:

We make the empty space as tall as the missing records in proportion to what the current rows take. In this example TOTAL_ROWS is a constant containing the total number of records. In a real life case, this piece of data would be a value obtained somehow from the server.

Now, we need to detect when the scrolling reaches the 'empty' space. To do that, we read the scrollTop property of the scrolling area and compare it to the height of the <tbody> section of the table, which contains the actual records. If the scrollTop is larger than the height of the <tbody>, the rows are completely hidden from view. In fact, we need to start filling it up before it goes completely away, we have to do it as soon as a sliver of 'empty' space starts showing up. To achieve that we substract the height of the visible area.

The second half of this code fetches a further batch of records once the 'empty' space becomes visible. In this example, the records are provided by a function which produces on the fly 20 records at a time with the first column holding the position and the second the batch the record belongs to. When you see a new value in the second column it means a new batch of records has been loaded.

There are two flickers in this example. One is because if a new batch of records has a field longer than any record already loaded, the table will suddenly widen to hold it. This can easily be solved by setting a fixed width on any records that might change in size. The other cause is that the new rows get added first and then the spacer height is adjusted so the knob on the scrollbar first goes up a little and then back again. Anyway, since the height of the spacer is an approximation, this is likely to happen anyway.