Recently, I delved into JavaScript and faced a dilemma with my Bitcoin Price update dashboard. The data is streaming in through an external WebSocket, updating the prices every second. But here's the catch - the table rows are going crazy! To maintain some sanity, I want to cap the table at 14 rows and continuously refresh it with new data from the WebSocket without expanding endlessly. Below, you'll find snippets of the code as well as the link to the external WebSocket.
If you have any suggestions on how I can dynamically insert rows into an HTML table, please share your wisdom. Much appreciated!
<script>
window.onload = () => {
function insertRow(price) {
var tr = document.createElement("tr"),
tdCoin = document.createElement("td"),
tdPrice = document.createElement("td"),
docFrag = new DocumentFragment();
tdCoin.textContent = "BTC";
tdPrice.textContent = `${Number(price.slice(0,-6)).toLocaleString("en-US")}`;
tr.appendChild(tdCoin);
tr.appendChild(tdPrice);
docFrag.appendChild(tr);
return docFrag;
}
var binanceSocket = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");
var table = document.getElementById("pricetable");
binanceSocket.onmessage = function(event) {
var messageObject = JSON.parse(event.data);
table.appendChild(insertRow(messageObject.p));
}
};
</script>
<table class="table table-striped">
<thead>
<tr>
<th>Coin</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody id="pricetable" class="crypt-table-hover"></tbody>
</table>