S R S R - 1 year ago 103
jQuery Question

Left-to-right scrolling on Datatable

I have a situation where I need to render a table using Datatables. However, I need to be able to sort it horizontally (left to right) instead of vertically (top to bottom). Is there any way I can do this?

Illustration: Columns are A,B,C,D,E. Rows are R1,R2,R3,R4...R30. I don't want to sort A to E, but I do want to sort any one of R1 to R30 so that A-E gets rearranged. For instance, for R1, the ascending order of values might be A,E,D,B,C and for R2's values, it might be D,E,B,A,C. I should be able to click on a row index (first column in that row) and see my columns reordered. (Default is rows being reordered)

Update: I found this example for horizontal sorting Sorting Table Columns with jQuery Table Sorter, but how do I get this to work with datatables?

Answer Source

you can use: columns().order()

var table = $('#example').DataTable();

    .columns( '.status' )
    .order( 'desc' )

More info: https://datatables.net/reference/api/columns().order()


You can achieve this by using the dataTables.colReorder.min.js plugin, you might want to disable the drag and drop initialy...in anycase:

var table = $('#example').DataTable({
    colReorder: true

table.on('click', 'td:first-of-type', function() {
  var values = [];
  var row = $(this).parent();


  var colOrder = values.sortIndices;


//get index after sort
//credit to this post:

function sortWithIndeces(toSort) {
  for (var i = 0; i < toSort.length; i++) {
    toSort[i] = [toSort[i], i];
  toSort.sort(function(a, b) {
    return a[0] - b[0]
  toSort.sortIndices = [];
  for (var j = 0; j < toSort.length; j++) {
    toSort[j] = toSort[j][0];
  return toSort;

Full working example here: https://jsfiddle.net/qjp8Lnam/6/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download