How to resize columns in datatables using callback method

Datatables

Sometimes we have some problems to configure the aspect of a datatable correctly for different reasons. I would like to you show how to solve it in an standard way.

After the table is loaded, it calls the callback method. And then we have to call to a fnAdjustColumnSizing in order to adjust all the columns in tha table. It’s important to enter only one time in this method. For this reason we have to control it adding an internal flag.

Javascript:

$(document).ready(function() {
  var isTableLoaded = false;
  var oTable = $('#example').dataTable( {
   "bAutoWidth": true, 
   "fnDrawCallback": function( oSettings ){
      if( !isTableLoaded){
           isTableLoaded = true;
           $('example').dataTable().fnAdjustColumnSizing();
      }
   }
  });
});

We can obtain more or less the same effect without calling a callback method but is better the first step:

$(document).ready(function() {
  var oTable = $('#example').dataTable( {
   "bAutoWidth": true
   }
  }).fnAdjustColumnSizing();

//Or

  var oTable = $('#example').dataTable( {
   "bAutoWidth": true
   }
  });
  oTable.fnAdjustColumnSizing();
});

Reference links: http://legacy.datatables.net/usage/callbacks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s