I have a large size of data to show as a table on my page and render a table with all the data is too heavy. So I want to show it as a virtual table that render cells only when necessary.
I know there is a way to fix the header and scroll the tbody, but by that way header widths must be fixed while I want the width could automatically changed according to the data.
So I consider to reuse a fixed number of rows to solve this problem.
I work this out, which works for mouse wheel, but I also want a scrollbar so that users without a mouse wheel could also scroll it.
function updateTable(event) {
var topIdTd = document.getElementById('data-0-id');
var topId = parseInt(topIdTd.innerHTML);
topId += event.deltaY;
for (var i = 0; i < 4; i++) {
document.getElementById('data-' + i + '-id').innerHTML = topId + i;
document.getElementById('data-' + i + '-value').innerHTML = 'looooooooooooooooooooong-value-' + topId + i;
}
return false;
}
var tbody = document.getElementById('table-body');
tbody.onwheel = updateTable;
table {
border-collapse: collapse;
}
table, td, th {
border: 1px solid gray;
}
th {
background-color: #eef;
}
<table>
<thead>
<tr>
<th>
ID
</th>
<th>
Value
</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
<td id="data-0-id">
0
</td>
<td id="data-0-value">
looooooooooooooooooooong-value-0
</td>
</tr>
<tr>
<td id="data-1-id">
1
</td>
<td id="data-1-value">
looooooooooooooooooooong-value-1
</td>
</tr>
<tr>
<td id="data-2-id">
2
</td>
<td id="data-2-value">
looooooooooooooooooooong-value-2
</td>
</tr>
<tr>
<td id="data-3-id">
3
</td>
<td id="data-3-value">
looooooooooooooooooooong-value-3
</td>
</tr>
</tbody>
</table>
How can I create a scrollbar on an unscrollable element?
Or is there any better solutions for this problem?