views:

343

answers:

1

Im working on building a jquery plugin to re-arrange the order of columns in a table NOT table rows!

I'm using the jquery ui draggable/droppable libraries to do this. The table header cells are the draggable elements. Once a header cell is dragged I want the helper element to be a cloned verson of the table column.

So far I've come up with this solution. The draggable 'start' function calls

$( ".selector" ).draggable( "option", "helper", my_custom_function);

which is passed a column index and returns a cloned table with all but the indexed column data removed. You can see a working example here: http://stucktogetherwithtape.com/code/columns

The problem is the custom helper element doesn't appear on the first drag, only on successive drags. I guess this is because it hasn't been added to the dom the first time the 'start' function is called.

Here's the javascript i've got so far:

$('table th')
.draggable(
  {
   appendTo: 'body',
   start: function(event, ui){
    // get column index
    var index = $(this).index();
    // create clone of dragged column to use as helper
    $(this)
     .draggable(
      "option",
      "helper",
      function(){
       // clone parent table
       var helper = $(this).closest('table').clone();
       // remove all table data apart from the indexed column
       return get_column(helper, index);
      }
     );
   },
  }
 );
/*
 * removes all table cells not at given index
 */
function get_column(table, index)
{   
 // ittereate through all rows in a table
 $(table)
  .find('tr')
   .each(
    // ittereate over all rows in table
    function(row_index, row_element){

     $(row_element)
      .find('td, th')
       // ittereate over all cells in table row
       .each(
        function(cell_index, cell_element){
         // remove all cells not matching the dragged index
         if(cell_index != index)
          $(cell_element).remove();
        }
       );
    }
  );
 return table;
}
+1  A: 

pah!

I'm making this way to hard for myself.

Worked out a simpler way to achieve this, viewable here: http://stucktogetherwithtape.com/code/columnise

th3hamburgler