Ways to toggle the visibility of HTML table rows periodically

I've been working with HTML tables, where I created a dynamic table split into four columns for display. Now, my task is to show 5 rows at a time on the screen using CSS. To achieve this, I'm populating the table in one go and refreshing the content every 5 seconds to display the next five rows until all data is loaded.

Approach Tried

var tableValue = [ // list of items and selling prices
    ...
]; 

myFun(); 
window.setInterval(showRows, 5000); 
showRows(); 

function myFun() {
    addTable(tableValue);
}

function showRows() {
    $(".hidden:lt(5)").removeClass("hidden");  // hide previous 5 rows and show next five
}

function addTable(tableValue) {
    var $tbl = $("<table />", { // create table
        "class": "table"
    }),
    
    $tb = $("<tbody/>"), 
    $trh = $("<tr/>");
    
    var split = Math.round(tableValue.length / 4); 
    for (i = 0; i < split; i++) {
        $tr = $("<tr/>", { 
            class: "hidden"
        }); //adding class 
        
        for (j = 0; j < 4; j++) {
            $.each(tableValue[split * j + i], function(key, value) {
                $("<td/>", {
                    "class": "text-left color" + (j + 1)
                }).html(value).appendTo($tr);
            });
        }
        $tr.appendTo($tb);
    }
    $tbl.append($tb);
    $("#DisplayTable").html($tbl);
}
tbody>tr>td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
  white-space: nowrap;
}

.color1 {
  background: #4AD184;
}

...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div id="DisplayTable">
</div>

Upon loading the page, the first 5 rows are displayed correctly. However, after 5 seconds, the next five rows render without hiding the first five rows.

Answer №1

To keep track of the rows that have been displayed, you should create a new CSS class that differs from "hidden" but still utilizes the display: none property. In this case, I've named it "already-displayed".

During each interval, apply this class to any rows that are not hidden and have not yet been shown.

var tableValues = [{
    "Item": "Product A",
    "Price": 50
  },
  {
    "Item": "Product B",
    "Price": 75
  },
  // Add more items as needed
];

myFunction();
window.setInterval(showRows, 5000);
showRows();

function myFunction() {
  addTable(tableValues);
}

function showRows() {
  $("tr:not(.hidden):not(.already-shown)").addClass("already-shown");
  $(".hidden:lt(5)").removeClass("hidden"); 
}

function addTable(tableValues) {
  var $table = $("<table/>", {
      "class": "table"
    }),
    $tbody = $("<tbody/>"),
    $headerRow = $("<tr/>");

  var splitValue = Math.round(tableValues.length / 4);

  for (i = 0; i < splitValue; i++) {
    $row = $("<tr/>", {
      class: "hidden"
    });

    for (j = 0; j < 4; j++) {
      $.each(tableValues[splitValue * j + i], function(key, value) {
        $("<td/>", {
          "class": "text-left color" + (j + 1)
        }).html(value).appendTo($row);
      });
    }

    $row.appendTo($tbody);
  }

  $table.append($tbody);
  $("#DisplayTable").html($table);
}
tbody > tr > td {
  white-space: nowrap;
  border-collapse: collapse;
  font-family: Verdana;
  font-size: 8pt;
  font-weight: bold;
}

.color1 {
  background: #C0FFEE;
}

.color2 {
  background: #FACADE;
}

.color3 {
  background: #DADADA;
}

.color4 {
  background: #BADA55;
}

.hidden,
.already-shown {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div id="DisplayTable">
</div>

Answer №2

The showRows() function you've created simply removes the hidden class, but it doesn't actually hide the previous five rows. Additionally, your selector targets elements with the hidden class, so even if you were to hide the previous five rows, they would just reappear. To address this issue, consider assigning an index to each table row and hiding items based on their respective indices. Alternatively, you could adjust your selector to specifically choose which five rows should be displayed.

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

To implement the ability to update the view in React.js, it is crucial to

I have successfully implemented the listing view and now I am facing an issue while passing data to the update view using the Id in the URL. The Id is being passed correctly in the URL, but the data saved to this particular Id is not being retrieved. When ...

What is causing the issue with this Ajax post not functioning properly?

In the code snippet below, an AJAX post request is made. The function widgets_positions() is responsible for gathering information about widgets positions on a webpage and sending it via AJAX. However, there seems to be a problem with how the 'widgets ...

Can an NPM package, originally developed with Angular 8 and converted to NPM, be utilized in JavaScript or React Native environments?

Looking to convert my Angular module (v8) into an NPM package in order to utilize it as a library within regular JavaScript, or even in a React or React Native application. Is this conversion feasible? ...

Setting up Webpack for react-pdf in a Next.js application

In my Next.js application, I am utilizing the react-pdf library to generate and handle PDF files on the client side without involving the server. However, I am facing challenges in setting up Webpack for Next.js as I lack sufficient expertise in this area. ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

How can I trigger a drop-down menu to appear when an image is clicked on in the exact same location

As part of my website development project, I am working on a page that displays a list of customers in rows. Each customer row includes different fields such as priorities assigned by the MD and CEO. Depending on the priority value, an image is displayed. ...

The print screen button in Internet Explorer is not functioning the same way as in other browsers when using JavaScript

Recently, I implemented a JavaScript code that restricts Normal users (non-professionals) from using print screen, Ctrl+A, and Ctrl+C functionalities on the browser. While this code works seamlessly on Firefox and Chrome, it seems to have intermittent su ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

Working with Vue: Retrieving component object attributes

Looking for a way to include a statement inside an element: v-if="currentstep < maxStep" I want to dynamically set the value of maxStep based on the number of components listed in my default export: export default { name: 'step', ...

Efficiently bundling Angular templates using Grunt and Browserify

I am currently utilizing angular1 in conjunction with browserify and grunt to construct my application. At present, browserify only bundles the controllers and retrieves the templates using ng-include through a separate ajax call. Due to the excessive amo ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

There is an issue with my HTML due to a MIME type error

I am currently facing an issue with my project. I have developed a node js server and now I want to display an HTML file that includes a Vue script loading data using another method written in a separate JS file. However, when I attempt to load the HTML f ...

How to update MongoDB documents with referenced objects using Mongoose?

Apologies for any language barriers. I am using node.js + express.js + mongoose.js Here is my schema in mongoose for groups: var groupSchema = new mongoose.Schema({ name: String, users: [{type: mongoose.Schema.ObjectId, ref: 'User'}] ...

What causes a user to log out when the page is refreshed in a React/Redux application?

Each time the page is reloaded in my React/Redux application, the user gets logged out, even though I have stored the token in localStorage. There seems to be an error somewhere. The token should ideally be saved when the user logs in and not lost upon rel ...

Retrieve the first item in each of the two arrays

I have a pair of arrays consisting of objects: var books = [ { id: 1, name: 'Book X' }, { id: 2, name: 'Book Y' } ]; var cars = [ { id: 1, name: 'Car P' }, { id: 2, name: 'Car Q' }, { id: 3, name: 'C ...

How can you simply hide Bootstrap alerts instead of deleting them when closing?

I am utilizing the power of Bootstrap 4 Alerts to showcase error messages, just like in their demo: <div class="alert alert-warning alert-dismissible fade show" role="alert"> <strong>Holy guacamole!</strong> You shou ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Retrieving information from a JSON file and displaying it in an HTML table through an asynchronous

I need to retrieve data from a server and display it in an HTML table. The server contains an array of weather forecast information as shown below. [{"date":"19\/08\/2020","weather":"Sunny","temperatur ...

What is the best way to display additional posts without having to reload the entire page?

I'm currently displaying the last three rows of my table on the home page using the following code: $result = mysql_query("SELECT id, title, date, text FROM news WHERE hshs=1 ORDER BY date DESC LIMIT $p") or die(mysql_error()); The value of $p is d ...

Tips for automatically selecting the day when choosing a date

I had created two fields named HolidayDate and HolidayDay with specific attributes as shown below: [Required] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] [DisplayName(Constants.DisplayN ...