Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data.

The entered data is then displayed in a table as a new row, with the most recent entry at the top.

What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over the table, I want it to expand and display all hidden rows. Once I move the cursor away, I want the table to collapse again, showing only the latest row.

I've been trying to implement this feature, but every attempt seems to make it worse, and currently, no new rows are being displayed for some reason.

Thank you in advance for any help!

Here is the code snippet:

HTML:

<body>
   <div class="container">
    <table id="myTable">
      <thead>
       <tr>
        <th>Name</th>
        <th>Number</th>
       </tr>
    </thead>
    <tbody>

    </tbody>
    </table>
 
    <form>
      <label for="fName">Name</label><br />
      <input type="text" id="fName" name="fName" /><br />
      <input type="submit" id="submitBtn" />
    </form>
  </div>

CSS:

table {
  color: black;
  width: 200px;
  border-collapse: collapse; 
  left: 100px;
  z-index: 1;
  position: absolute;
  box-shadow: 0px 2px 5px black;
}

.expand{
display: table-row !important;
}

 .collapse{ 
display: none;
}

 tr:not(:first-child){
display: none;
}

JS:

"use strict";

let inputBox = document.querySelector("#fName");
let tBody = document.querySelector("tbody");
const table = document.querySelector('table');

function addRow() {

  let row = tBody.insertRow(0);
  let cell1 = row.insertCell(0);
  let cell2 = row.insertCell(1);
  cell1.innerHTML = inputBox.value;
  cell2.innerHTML = "text2";
  inputBox.value = " ";
  row.classList.add('tr');
  
}

tBody.classList.add('collapse');

document.querySelector("#submitBtn").addEventListener("click", function (event) {
    event.preventDefault();
    addRow();
  });

  // Expand/collapse event listeners:
  
  table.addEventListener('mouseover', function(){
    tBody.classList.remove('collapse');
    tBody.classList.add('expand');
  })

  table.addEventListener('mouseout', function(){
    tBody.classList.remove('expand');
    tBody.classList.add('collapse');
  })

Answer №1

Your code implementation requires a small adjustment. Within the addRow() function, ensure that the newly added row is visible while hiding the others.

function addRow() {

  let row = tBody.insertRow(0);
  let cell1 = row.insertCell(0);
  let cell2 = row.insertCell(1);
  cell1.innerHTML = inputBox.value;
  cell2.innerHTML = "text2";
  inputBox.value = " ";
  row.classList.add('tr');
  
/* Adjustments needed here */
  tBody.classList.remove('expand');
  tBody.classList.add('collapse');

Additionally, in the CSS file, modify the expand and collapse classes as shown below:

/* Hides all rows except the first one */
.collapse tr:not(:first-child) { 
  display: none;
}

/* Shows all rows */
.expand tr {
  display: table-row;
}

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

Difficulty linking CSS to HTML in a Flask web application

My HTML/CSS file is pretty straightforward: <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <meta name=&quo ...

The color of the SVG is not visible in the PNG rendition

I have applied a style to an svg image and successfully changed the fill color using a random colors function in JavaScript. However, when I convert the svg to a png format after making these color changes, the PNG file retains the original colors instead ...

Object displaying no visible illumination

Recently, I've been experimenting with this project, and after some trial and error, I've managed to get things working to some extent. As a novice in JavaScript, I'm unsure if the issue I'm facing has a simple solution. The problem is ...

How can you show several copies of an image on an HTML page?

I am trying to show an image multiple times in a row using a combination of HTML, PHP, and CSS. Here is my code snippet: for ($i=20; $i<=320; $i=$i+300) { echo "<style> " . ".test{" . "position: absolute; left: " . $i . ...

Does Google Cloud CDN not store data from the storage bucket?

I've been experimenting with combining a Load Balancer, Cloud Storage, and CDN for the past few weeks. Unfortunately, I have not been successful in getting it to work as expected. I uploaded some static files (2 jpgs, svgs, and css files) to a multi- ...

Animate the React Bootstrap modal only when it is shown or hidden

I am experimenting with the idea of transitioning smoothly from one modal to another in bootstrap Modals for react (using react-bootstrap). However, I am facing challenges due to the fade CSS class causing flickers and unwanted animations. My goal is to h ...

How to enable the Copy to Clipboard feature for multiple buttons and transition from using an ID to a class identifier

Can someone please assist me? I have a copy to clipboard function that works well for IDs and a single button on my website. However, I need to modify it to work for multiple buttons and values with a class identifier. Unfortunately, I am unsure how to mak ...

Guide to uploading multiple images to an Amazon AWS S3 bucket using Node.js, Angular, and JavaScript

Can anyone share insights on where and how E-commerce websites typically upload their product images? Has anyone had experience using Amazon AWS S3 bucket for this purpose? Additionally, does anyone know how to upload or retrieve multiple images at once ...

Issues with Bootstrap indicators and slide controls functionality are being experienced

I am currently exploring a method to create a carousel with thumbnails by referring to this example. I have followed their instructions closely, but unfortunately, clicking on the thumbnails and indicators does not seem to be working as expected. The onl ...

Filtering an array by a search term

How do you filter an array based on a specific search term? For example, if we have an array [Tom Harry, Tom John, John Glen, Tom Harward] and we search for "Tom H," then only Tom Harry and Tom Harward should be the output. [Tom Harward, Tom Harry]; Usin ...

using javascript to trigger android function

Looking to create a button in HTML that triggers a call from an Android device via JavaScript. Here is the code snippet I have tried, but it's not functioning as expected. Please note, I am new to Android development: public class MainActivity extend ...

Disable the toggling of the dropdown functionality in the bootstrap function

Recently, I made some modifications to a bootstrap navbar by transforming it into a toolbar and adjusting a dropup dropdown to include two datepicker elements. An issue arose when the dropdown would collapse upon selecting a date. To address this problem, ...

Submitting buttons by using a textbox array is a simple process

I need help figuring out why my buttons are not working on a page I'm creating with around 300 textboxes generated from a foreach loop. While I've successfully been able to write links into the textboxes, I am struggling to read the textboxes arr ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

Manipulating contextual selectors

Have you ever tried reverting or overriding attributes from contextual selectors? .card { padding-top: 20px; ... } .card .card-header { padding: 0 20px; } .card .card-header.news { padding-top: 0px; } Do you think it's possible to elimina ...

Leveraging jQuery to implement onclick functionality within a Jinja2 loop

I'm currently working with Python, Flask, and Jinja2. When using a for loop, I want to be able to click on the {{ place.place_photo }} element to toggle its details. Initially, I had it functioning correctly but ran into an issue where clicking on on ...

Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows: By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg. This will result in the stub executing the first callback it ...

The importance of CSS style prioritization

I can't seem to figure out CSS declaration priority. I have an external CSS file with a rule and some inline CSS declarations that are supposed to override it. According to my understanding, inline styles should take precedence over external CSS rules ...

What is the reason behind Intellij Code Inspection indicating that a selector is not being used?

I have a small project consisting of two files located in the same folder. App.css .App-align-left { text-align: left; } App.js import React from 'react'; import 'App.css'; class App extends React.Component { constructor(p ...

Guide to placing the cursor at a specified position within an editable content div

I am struggling with a div <div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?..."> Some Text will be inserted here. </div ...