Force column width with dataTables 2.3.7
Force column width with dataTables 2.3.7
Link to test case: https://elk.2n-tech.com/
Debugger code (debug.datatables.net): eqaroc
Description of problem: Hello, I am trying to force a column with hidden data, using dt-control to display an arrow instead, to a size that would be just enough for that arrow (30px). But using columnDefs with { width: 30, targets: 0 } or { width: '30px', targets: 0 }, does not seems to do anything.
Could you help me please?
var table = new DataTable('#example table', {
scrollY: 300,
'dom': 'tr',
order: [[2, 'desc']],
columnDefs: [
{ orderable: false, targets: 0 },
{ className: 'dt-control', targets: 0 },
{ width: 30, targets: 0 }
],
});
table.on('click', 'td.dt-control', function (e) {
let tr = e.target.closest('tr');
let row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
}
else {
// Open this row
let cell = $(tr).find('.details');
row.child(cell.html()).show();
}
});
<style>
.hidden {
display: none;
}
</style>
<div id="example">
<table>
<thead>
<tr>
<th></th>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</thead>
<tbody>
<tr >
<td>
<div class="hidden details">
<div>
<ul>
<li>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris dolor nisl, fringilla sed sodales vehicula, finibus non turpis.
Etiam non diam magna. Integer vel mauris scelerisque, faucibus dui ut, pellentesque tortor.
</li>
<li>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris dolor nisl, fringilla sed sodales vehicula, finibus non turpis.
Etiam non diam magna. Integer vel mauris scelerisque, faucibus dui ut, pellentesque tortor.
</li>
</ul>
</div>
</div>
</td>
<td>Lorem ipsum dolor sit amet</td>
<td>Lorem ipsum dolor sit amet</td>
<td>Lorem ipsum dolor sit amet</td>
<td>Lorem ipsum dolor sit amet</td>
</tr>
Answers
Let me explain what is happening first:
DataTables creates a "worst case" table that is used for sizing the columns so they don't jump around when paging. It uses a few techniques to do that - it gets the longest strings from each column, and also the longest words from each column - puts them in the sizing table as separate rows and reads the optimal sizes back.
Because it is string based there are a lot of nuances that it misses - for example the longest word part doesn't "know" that the details are hidden, and thus it does pick out long words - giving rise to the issue you are seeing.
How to fix it:
1) Using the current nightly version (which will be 2.3.8 in the near future) you can change
<div class="hidden details">to be a<template>tag - example here.2) The second option, keeping the current markup, is to put the details into a hidden column. Example here.
Ideally DataTables would handle what you are giving it without any extra consideration, but the sizing table using strings (which it does for performance) are tripping it up.
Allan