JSFiddle - React, Tailwind, and code Playground
by oysteinmoseng
HTML
<h1>
Data grid render test
</h1>
<div id="controls">
<label>Num cells: <input id="numCells" type="number"></label>
<button id="go">
Go
</button>
</div>
<div>
<div id="container"></div>
</div>
CSS
#controls {
margin: 20px 0;
}
#container {
height: 700px;
width: 1000px;
overflow: scroll;
display: grid;
grid-template-columns: repeat(20, 1fr);
}
.cell {
background-color: #eef;
border: 1px solid #ccc;
margin: 2px;
text-align: center;
padding: 4px;
}
.cell:hover {
background-color: #a0ffa0;
transform: scale(1.1);
}
JavaScript
class BufferedScroll {
constructor(container, viewSize) {
this.container = container;
this.viewSize = viewSize;
this.elements = [];
}
addElement(element) {
this.elements.push(element);
this.updateView();
}
reset() {
this.elements = [];
this.container.innerHTML = '';
}
updateView() {
this.container.innerHTML = '';
this.elements.slice(0, this.viewSize).forEach(el => this.container.appendChild(el));
}
}
function makeCell() {
const cell = document.createElement('div');
cell.textContent = ~~(Math.random() * 10000);
cell.classList.add('cell');
return cell;
}
const scroller = new BufferedScroll(document.getElementById('container'), 100);
document.getElementById('go').onclick = () => {
const numCells = parseInt(document.getElementById('numCells').value, 10);
scroller.reset();
if (numCells) {
for (let i = 0; i < numCells; ++i) {
scroller.addElement(makeCell());
}
}
};