Automatically clear out table rows once the maximum row limit is reached, then append new data using the WebSocket data in JavaScript

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>

Answer №1

To retrieve all rows from your table, you can use the querySelectorAll("tr") method. If you need to delete elements from your table, you can utilize the removeChild method.

If you want to ensure that your table does not exceed a certain number of rows (x), you can implement the following logic:

const rows = table.querySelectorAll("tr");
if (rows.length > 14) table.removeChild(rows[0]);

Here is a functional demonstration:

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"I'm trying to figure out the best way to use Selenium and Python to send a character sequence to a contenteditable element that has its attribute set

Recently, I've been experimenting with using Python 3.6 and Selenium to automate a simple task - logging into a chat website and sending messages automatically. is the webpage where I want to send the messages. Despite my limited experience with Py ...

Show a plethora of images using the express framework

I have two closely related questions that I am hoping to ask together. Is there a way for express (such as nodejs express) to handle all requests in the same manner, similar to how http treats requests with code like this: pathname = url.parse(request.url ...

Using Moment JS to display the days of the upcoming week

I'm in the process of developing a weather application and I need to create code that will display the upcoming week's weather forecast. The only information I have from the server is a "time" entity with a "value" set for next Monday such as "20 ...

Attempting to generate a fresh document by duplicating the data from a specific variable

Currently attempting to generate a new csv file within a specific directory. The goal is to save the data of a variable inside the created csv file: handleRequest(req, res) { var svcReq = req.body.svcReq; var csvRecData = JSON.stringify(req.bod ...

Leveraging the power of React's callback ref in conjunction with a

I'm currently working on updating our Checkbox react component to support the indeterminate state while also making sure it properly forwards refs. The existing checkbox component already uses a callback ref internally to handle the indeterminate prop ...

Error encountered while attempting to save user to mongoose due to bcrypt issue

I am currently dedicated to expanding my knowledge in node and react through a tutorial. If you want to check out the repository, here is the link: While making a post request to /api/users/register, I encountered an error that seems to stem from an unde ...

Tips for accessing the JSON file containing Spark driver metrics:

After following the monitoring guide at , I tried configuring the metricsservlet but found the documentation to be lacking in useful information. According to the commons in metrics.properties: "5. MetricsServlet is added by default as a sink in master, ...

Tips for bringing a StrongLoop API into a JSON or YAML format

I am utilizing an API that was created using loopback/strongloop and currently running smoothly. My goal is to export this generated API in YAML or JSON format so that I can reuse it in another application. Specifically, I am seeking the swagger.json file ...

Reverse the color of H1 text within a vertical div

Is it feasible to reverse the coloring of a segment within an h1 element using a div, horizontally? Refer to the illustration shown in the image below. https://i.sstatic.net/QAKwD.jpg ...

Unable to generate JSON: Serializer not found for class org.json.JSONObject and no properties found to create BeanSerializer

I am trying to set the response as JSON, but I keep encountering this issue: Could not write JSON: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature. ...

Looking for a JavaScript function that will enable the acceptance of commas and spaces

How can I modify this integer validation function to allow for commas and spaces to be entered during the keydown event? function intValidate(event) { if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || even ...

Can the distinction between a page refresh and closure be identified using the method below?

My idea is to trigger a popup window when the page is closed, not when it is refreshed. The plan is as follows: Client Send an ajax request to the server every x seconds. Server var timeout=0 var sec=0 while (sec>timeout) { open popup win ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Struggling with jQuery fadeIn and fadeOut in IE8?

I am struggling to understand why my fadeIn, fadeOut, and corner() functions are not working in IE8 on my website at . They were functioning properly before, but now they seem to be broken. Can anyone pinpoint the issue causing this problem? If you click ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

Create a duplicate of array A in JavaScript with the keys transferred to array B, then make modifications to the elements in

Currently, I am delving into JavaScript in regards to array assignment and cloning. A puzzling issue arises when attempting to clone the elements of array A into array B using the spread operator "...". Surprisingly, when modifying the elements in array B, ...

Retrieve a file from an AWS S3 bucket using AngularJS

Currently utilizing angularjs. I am in need of incorporating a download feature. <button class="btn btn-labeled btn-info" title="download"> <a href="link provided by s3" download="downloaded">Download</a> </button> I have ...

Capturing user input by detecting the Enter key using jQuery

I am brand new to coding and struggling with capturing user input when the enter key is pressed. Currently, I have a submit button that successfully captures user input upon clicking. <div> <div class="text-area"> <li class=" ...

Having trouble setting a value as a variable? It seems like the selection process is not functioning properly

My Hangman game has different topics such as cities and animals. When a user selects a topic, the outcome should be a random item from that specific topic. For example: London for cities or Zebra for animals. Currently, I am only generating a random lett ...

Looking for an easy solution in RegExp - how to locate the keys?

Similar Inquiries: Retrieving query string values using JavaScript Utilizing URL parameters in Javascript I am tasked with extracting specific keys from a series of URLs where the key is denoted by 'KEY=123'. My goal is to identify and e ...