Foliotek Developer Blog

Make Table Rows Sortable Using jQuery UI Sortable

So you want to make table rows sortable using jQuery UI? Luckily, the Sortable interaction does most of the work for you.

But there’s a catch: one problem that I ran into when implementing this (with UI version 1.7) was the cell widths of the row would collapse once I started dragging it.

Suppose you have a table of data, like this one:

<table class="grid" id="sort" title="Kurt Vonnegut novels">  
<tr><td>1952</td><td>Player Piano</td><td>B</td></tr>  
<tr><td>1963</td><td>Cat’s Cradle</td><td>A+</td></tr>  
<tr><td>1973</td><td>Breakfast of Champions</td><td>C</td></tr>  
<tr><td>1965</td><td>God Bless You, Mr. Rosewater</td><td>A</td></tr>  

Your first attempt to make it sortable might look like this:

 $(“#sort tbody”).sortable().disableSelection();  

And it actually works, but there is a bit of a problem. The cell widths seem to be collapsing once you start dragging a row (notice how close the “C” cell is to the “Breakfast of Champions” cell). It looks like this:

Sortable row collapsed widths

The problem has to do with the helper object. The helper object is basically the DOM element that follows the cursor during the drag event. When it is created by default, the cells collapse to the size of the content inside of them.

You can specify a function that returns a jQuery object to create a custom helper object. By creating a function that will keep the cell widths consistent, this problem can be fixed.

**Update:** I have posted a [jsFiddle demo of table sorting with jQuery UI]( to show how the fix works. There is another fix, [proposed on StackOverflow]( that includes cloning the original row (to not set the width permanently). This is also included in the jsFiddle.
// Return a helper with preserved width of cells  
var fixHelper = function(e, ui) {  
  ui.children().each(function() {  
  return ui;  
$(“#sort tbody”).sortable({  
 helper: fixHelper  

Now it works as expected:
Sortable row fixed