Issue
I am facing a challenge with two DataTables — one with five columns and the other with four columns. My goal is to find a solution for hiding certain columns based on specific screen widths.
Approaches I've Tested
While resizing the browser, both tables automatically switch to a two-column layout when the width reaches 480 pixels. However, I require additional breakpoints in between to hide more columns that do not fit within the viewport.
- Attempted adding a
responsive
class to the table similar to the example shown here - Experimented with using column control helper classes to eliminate columns at specific breakpoints, but even the
none
class did not hide a column - Assigned classes to the
<th>
elements in thethead
section to leverage their responsive breakpoints - Included
responsive: true
in my DataTables configuration 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",
"render": $.fn.dataTable.render.number( ',', '.', 1, '', '%' )
},
{
"data": "test_takers",
"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>