Problem
I have two DataTables — one is five columns and the other is four columns — and I'm looking for a way to hide columns at specific screen widths.
What I've tried
When I resize the browser, both tables automatically appear to drop down to a two-column chart at 480 pixels in width, but I need additional breakpoints in-between where I'm dropping additional columns since they don't fit inside viewport.
- Adding a class of
responsiveto the table as seen in this example - I've tried using column control helper classes to remove columns at certain breakpoints, but even adding the class
nonedid not hide a column - Adding classes to the
<th>in thetheadto take advantage of their responsive breakpoints - I've include
responsive: truein my DataTables options
scripts.js
$('#test-scores').dataTable({
initComplete: function () {
this.api().columns([0,1,2]).every( function () {
var column = this;
var colIdx = column.index();
// adjust label for dropdown according to index
// TODO - colIdx is producing 0
if (colIdx === 0) {
var label = 'districts';
}
else if (colIdx === 1) {
var label = 'schools';
}
else {
var label = 'subjects';
}
var select = $('.select--map-' + label)
.on( 'change', function () {
var val = $(this).val();
if ( val == '*' ) {
column
.search( '' )
.draw();
}
else {
val = $.fn.dataTable.util.escapeRegex( val );
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
}
});
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
});
});
},
"pageLength": 25, // The number of entries per page
"order": [0, 'asc'], // First column in ascending order, previous "3, desc"
"responsive": true,
"searching": true,
"columns": [
{ "data": "district",
"render": function (data, type, row, meta) {
return '<a href="/schools/' + makeSlug(data) + '">' + data + '</a>';
}
},
{ "data": "school",
"render": function (data, type, row, meta) {
return '<a href="/schools/' + makeSlug(row['district']) + '/' + makeSlug(data) + '">' + data + '</a>';
}
},
{ "data": "subject" },
{
"data": "rate",
// https://datatables.net/manual/data/renderers#Built-in-helpers
// Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
"render": $.fn.dataTable.render.number( ',', '.', 1, '', '%' )
},
{
"data": "test_takers",
// Render.number() parameters: thousands separator, decimal separator, decimal places, prefix, suffix
"render": $.fn.dataTable.render.number( ',', '.', 0, '', '' )
}
],
"ajax": {
"url": "{% static 'schools/json/school_map_scores.json' %}"
}
});
index.html
<table id="test-scores" class="table table-striped responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th class="table-district none">District</th>
<th class="table-school none">School</th>
<th class="table-subject none">Subject</th>
<th class="table-proficiency none">Pct. proficient</th>
<th class="table-testtakers none">No. of test takers</th>
</tr>
</thead>
<tbody></tbody>
</table>