I am new to JavaScript, not sure if this very basic question. I've created a Bitcoin Price update dashboard using the data fetched from the external WebSocket. I managed to get the data from the WebSocket and display it on the HTML table. The price updates every seconds, So the table rows are going insane. I want to limit the Table row for 14 rows and after the table get 14 rows i want to delete that data and import new data with the Websocket without increasing the HTML table rows. I tried my best to explain.
I have provided the code snippets below as well as external Websocket from where I am pulling the data.
Please let me know how should I insert the row dynamically into a HTML table. Thank you so much in advance
<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"),
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>
You can get all rows in your table using querySelectorAll("tr")
. You can remove elements from your table using removeChild
.
So, to make sure your table never grows past x
rows, you do:
const rows = table.querySelectorAll("tr");
if (rows.length > 14) table.removeChild(rows[0]);
Here's a working example:
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"),
table = document.getElementById("pricetable");
binanceSocket.onmessage = function(event) {
var messageObject = JSON.parse(event.data);
table.appendChild(insertRow(messageObject.p));
const MAX_ROWS = 5;
const rows = table.querySelectorAll("tr");
if (rows.length > MAX_ROWS) table.removeChild(rows[0]);
}
}
<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>