Skip to content
Advertisement

Keep table height fixed i.e., inside a block , and also add a scrollview inside my table

I have an html table which shows all the records fetched from mysql database. This is my table created:

<table id="employee_details" border="2"></table>

My css:

#employee_details{
  display:none;
  position: absolute;
  top:15em;
  left:20em;
  width:75em;
}

#employee_details td{
  height:60px;
  text-align: center;
  width:12em;
}

Now, in my javascript, I create the table rows and cells dynamically, based on the number of records fetched. This is my code snippet:

var count=0;
success:function(response){
      const arr = JSON.parse(response);
      table.style.display="block";
      
      for(var i=0; i<arr.length; i++){

          var row = table.insertRow(count);  
          var cell = row.insertCell(0);
          var cell1 = row.insertCell(1);
          var cell2 = row.insertCell(2);
          var cell3 = row.insertCell(3);
          var cell4 = row.insertCell(4);
          var cell5 = row.insertCell(5);
          var cell6 = row.insertCell(6);
          var cell7 = row.insertCell(7);
      
          //cell.innerHTML = arr[count] for all the rows
          
          count++;
       }
}

So, for each response, it creates a row and inserts the values to its appropriate cells. So, the table height is dynamic (it depends on the number of records fetched).

What I want is the table to have a fixed height (inside a block), inside which there will be a vertical scrollbar which you can use to scroll up and down to view all the records. Along with that the first row table.rows[0] should be freezed so that it doesn’t move along with the scroll (as it contains the label for each cell).

How do I do that? Any help would be appreciated.

Advertisement

Answer

One way is that you have to wrap your table inside a div and then use overflow: auto; to that div.

Here is the example https://codepen.io/rk-v/pen/BaRqPoB

Advertisement