I am working with a Bootstrap DataTable that includes a sparkline in the last column. Here is the complete JavaScript code:
$(document).ready(function() {
var groupColumn = 0;
let table = $('#example').DataTable({
//responsive: true,
autoWidth: true,
processing: true,
ordering: true,
scrollY: '50vh',
scrollCollapse: true,
paging: false,
searching: true,
ajax: {
url: "api/ApartmentsAvailables",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
},
columnDefs: [{
visible: false,
targets: groupColumn
},
{
targets: 7,
render: DataTable.render.datetime('YYYY-MM-DDT00:00:00', 'MMMM D, YYYY', 'en'),
},
{
responsivePriority: 1,
targets: 0
},
],
order: [
[groupColumn, 'asc']
],
drawCallback: function(settings) {
$('.sparkline')
.map(function() {
return $('canvas', this).length ? null : this;
})
.sparkline('html', {
type: 'line',
width: '250px'
})
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var last = null;
api
.column(groupColumn, {
page: 'current'
})
.data()
.each(function(group, i) {
if (last !== group) {
$(rows)
.eq(i)
.before('<tr class="group" style="background-color:DarkGray; text-align:center;font-weight: bold; color:white;"><td colspan="8">' + group + '</td></tr>');
last = group;
}
})
},
columns: [
{
data: "building"
},
{
data: "floor_Plan"
},
{
data: "apt_Number"
},
{
data: "rent"
},
{
data: "bedrooms"
},
{
data: "bathrooms"
},
{
data: "sqft"
},
{
data: "available_Date"
},
{
data: 'prices',
render: function(data, type, row, meta) {
return type === 'display' ?
'<span class="sparkline">' + data.toString() + '</span>' :
data;
}
},
]
});
new $.fn.dataTable.FixedHeader(table);
// Order by the grouping
$('#example tbody').on('click', 'tr.group', function() {
var currentOrder = table.order()[0];
if (currentOrder[0] === groupColumn && currentOrder[1] === 'asc') {
table.order([groupColumn, 'desc']).draw();
} else {
table.order([groupColumn, 'asc']).draw();
}
});
});
The issue arises when I activate responsive: true
. The sparkline column gets hidden, and upon expanding the row to reveal the hidden columns, it displays the entire array of values instead of the sparkline.
It seems that the
drawCallback: function (settings) {
$('.sparkline')
.map(function () {
return $('canvas', this).length ? null : this;
})
.sparkline('html', {
type: 'line',
width: '250px'
})
cannot be applied to a hidden column.
When the responsive option is disabled, the generated HTML for the td is:
<td>
<span class="sparkline">
<canvas style="display: inline-block; width: 250px; height: 21px; vertical-align: top;"
width="250"
height="21"/>
</span>
</td>
With the responsive set to true:
<td style="display: none;"
class="dtr-hidden">
<span class="sparkline">3446,3446,3416,3416,3416,3546,3546,3546,3546,3546,3546,3561,3556,3551,3396,3396,3396,3346,3306,3306,3306</span>
</td>
I believe I need to somehow capture the click on the expand icon and then re-insert the canvas, but I am unsure how to accomplish this.