Wednesday, January 30, 2013

DataTables Fixed Height

I've already confessed that I am a big fan of Twitter Bootstrap and jQuery. In my apps I often deal with tables and grids. In the past I was using the wonderful ExtJS grid. But ExtJS is rather heavy and it does not play well with Bootstrap. So I was looking at alternatives, and there is a nice (and free!) jQuery Plugin for this: DataTables.
While DataTables gives you a lot of flexibility I could not find a nice way of having the table's height fixed. There is a discussion on their forum for this topic but the solution did not work that well for me so I came up with a simpler alternative that seems to work well. The following JS snippet refers to the examples on DataTables website.
$table = $('#example');
$table.dataTable( {
  "sDom": 'tif', 
  "bScrollInfinite": true, 
  "bScrollCollapse": true, 
  "sScrollY": "200px",
  "oLanguage": { 
    "sLengthMenu": "_MENU_ / page",
 "sInfo": "(_START_ to _END_) of _TOTAL_",
 "sSearch": ""
  }
  ,"fnDrawCallback": function() {
        $table.dataTable()._fnScrollDraw();        
        $table.closest(".dataTables_scrollBody").height(200);
   }  
} );
From the snippet above, only the fnDrawCallback is important. It will fix the table's height to 200px as instructed in the scroller configuration. The trick is to let the component do its work and then simply adjust the height of the scroller element.
A better version would not duplicate the height and would reuse the value configured in sScrollY property, but I did not find yet how to access it.

3 comments:

Sharmila said...

this is not working for me, could you pl post complete working example?

Thanks

Anonymous said...

Many thanks! Worked for me.

Unknown said...

Nice. Thank you.