Resizable table columns

cybermotron picture cybermotron · Oct 19, 2010 · Viewed 14.7k times · Source

I'm developing a web app and am looking for a way to create my own datagrids.

I know that there are lots of fantastic scripts out there with all the bells and whistles, but I need my own specific functionality, css styling, and the ability to use my own ui controls in it.

Really, the only thing I need is the ability to resize the columns. I don't really care if the markup doesn't maintain the row structure or isn't semantic, because all of the data will be populated by ajax requests.

I was thinking a possible solution would be to make each column a div.

Is there a tutorial out there that can help me?

Answer

Ingo picture Ingo · Aug 8, 2012

I recommend to use jQuery UI Resizable with some enhancements. The plugin really focuses only on resizing and enables full customization since you can add your own callback functions at any event. By default, however, the plugin cannot reize table headers, but I could make it running with valid HTML, updating the table's COLGROUP area on resize.

The concrete idea would be:

  1. The HTML table specifies the initial width in its COLGROUP area and has CSS property table-layout:fixed.
  2. Decorate TH elements with jQuery UI’s .resizable().
  3. On resizing start: Find the matching COL element of active TH and remember original width.
  4. On resizing: Calculate the resize delta and update (increase/decrease) the selected COL element. This will resize the whole column with every browser.

Plugin init:

$(".resizable th").resizable({
 handles: "e",

 // set correct COL element and original size
 start: function(event, ui) {
   var colIndex = ui.helper.index() + 1;
   colElement = table.find("colgroup > col:nth-child(" +
   colIndex + ")");

   // get col width (faster than .width() on IE)
   colWidth = parseInt(colElement.get(0).style.width, 10);
   originalSize = ui.size.width;
 },

 // set COL width
 resize: function(event, ui) {
   var resizeDelta = ui.size.width - originalSize;

   var newColWidth = colWidth + resizeDelta;
   colElement.width(newColWidth);

   // height must be set in order to prevent IE9 to set wrong height
   $(this).css("height", "auto");
 }
});

I described the full solution including JavaScript, HTML markup, cross-browser CSS and Live-Demo at http://ihofmann.wordpress.com/2012/07/31/resizable-table-columns-with-jquery-ui/