JSFiddle - React, Tailwind, and code Playground
by dinesh_raja
HTML
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.css">
<script src="https://cdn.datatables.net/v/dt/dt-1.10.16/datatables.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/jeffreydwalter/ColReorderWithResize@9ce30c640e394282c9e0df5787d54e5887bc8ecc/ColReorderWithResize.js"></script>
<h3><a target="_blank" href="https://www.gyrocode.com/articles/jquery-datatables-column-reordering-and-resizing/">jQuery DataTables: Column reordering and resizing</a> <small>Allow resizing only</small></h3>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
JavaScript
$(document).ready(function () {
var page_load = true;
var new_array = [];
var table = $('#example').DataTable({
"ajax": {
"url": "https://gyrocode.github.io/files/jquery-datatables/arrays.json",
"type": "GET",
"dataType": "json",
"complete": function(res) {
console.log("api complete");
new_array.map(function(v, i) {
$("#example thead tr th").eq(i).width(v);
});
page_load = false;
}
},
'dom': 'Rlfrtip',
'stateSave': true,
'colReorder': {
'allowReorder': true
},
stateSaveCallback: function (settings, data) {
if(page_load == false) {
var columns = data['columns'];
$.each(columns, function (index, el) {
data['columns'][index]['width'] = $("#example thead tr th").eq(index).width();
});
console.log(data);
$.ajax({
"url": "https://blakbit.com/dt_test.php?id=example",
"data": data,
"dataType": "json",
"type": "POST",
"success": function () { }
});
}
},
stateLoadCallback: function (settings, callback) {
new_array = [];
$.ajax({
url: 'https://blakbit.com/dt_test.php?id=example&load',
dataType: 'json',
//async : false,
success: function (json) {
console.log("json ", json);
var table_columns = json.columns;
// let load_index = 0;
for(var i = 0; i < table_columns.length; i++) {
if(table_columns[i].visible == true) {
var width = table_columns[i].width;
if(width) {
new_array.push(width);
}
}
}
callback(json);
}
});
}
});
});