I have an input field where i put data in.
that data goes to a table and creates a new row, with the data in it.
the newest row is always on the top.
I want the table to show only the newest row and hide all the rest (meaning showing only one row), and when i mouseover it using an event listener I want it to expand and show all other rows that were hidden. when I mouseout, I want the table to collapse again and show only the newest row while hiding all the rest.
how can i do that? every time i try to fix this i just make it worst right now i doesnt show new rows at all for some reason.
thanks in advance!
thats my code:
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();
});
// collapst/expand 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');
})
It seems your implementation needs a bit of adjustment. In addRow() function, ensure that the newly added row is displayed while others are hidden.
Also in css file modify the expand and collapse classes as follows: