tru7
tru7

Reputation: 7232

Freeze width of columns in table already rendered

With a table already rendered, if I hide some row the width of the columns is dynamically recalculated per the contents:

function switchRow(ixRow){

let table = document.getElementById('theTable');

let row = table.rows[ixRow];
let currentVisibility = row.style.display;

row.style.display= currentVisibility== 'none' ? 'table-row' : 'none';

}
table{
  border: 2px solid black;
  padding: .5em;
}
<table id='theTable'>
<tr><td>Hellen</td><td>Smith</td></tr>
<tr><td>Montgomery</td><td>Wolfeschlegelsteinhausenbergerdorff</td></tr>
</table>
<br>
<button onclick="switchRow(1)">Switch row 1</button>

Is there a simple way to "freeze" the width of all the columns after the first rendering so hidding/displaying keeps the witdh of all the table / columns?

Edit to differentiate from the other question supposedly duplicated What I am looking for is to keep the widths that have been calculated when the table has been rendered -whatever the rules explicit or implicit-. Once displayed the widths must be constant. I do not want to add any width prior rules, I want the default rendering of the table but once rendered I look for no dynamic changes in widths.

Upvotes: 0

Views: 360

Answers (1)

0xc14m1z
0xc14m1z

Reputation: 3725

I would first compute the maximum cell widths after the page load and assign it to the cells, in order to be kept for later:

window.onload = function () {
   const table = document.getElementById('theTable');
   const widths = computeColumnWidths(table)
   setColumnWidths(table, widths)
}

function computeColumnWidths(table) {
  const widths = Array.from({ length: table.rows[0].cells.length })
                      .fill(0);
  
  for (let i = 0; i < table.rows.length; i++ ) {
    const row = table.rows[i]
    
    for (let j = 0; j < row.cells.length; j++) {
      const cell = row.cells[j]
      widths[j] = Math.max(widths[j], cell.offsetWidth);
    }
  }
  
  return widths;
}

function setColumnWidths(table, widths) {
  for (let i = 0; i < table.rows.length; i++ ) {
    const row = table.rows[i]
    
    for (let j = 0; j < row.cells.length; j++) {
      const cell = row.cells[j]
      cell.style.width = widths[j] + 'px';
    }
  }
}

function switchRow(ixRow){

  let table = document.getElementById('theTable');

  let row = table.rows[ixRow];
  let currentVisibility = row.style.display;

  row.style.display = currentVisibility == 'none' ? 'table-row' : 'none';

}
table{
  border: 2px solid black;
  padding: .5em;
}
<table id='theTable'>
<tr><td>Hellen</td><td>Smith</td></tr>
<tr><td>Montgomery</td><td>Wolfeschlegelsteinhausenbergerdorff</td></tr>
</table>
<br>
<button onclick="switchRow(1)">Switch row 1</button>

Upvotes: 1

Related Questions