Jon Gauthier Jon Gauthier - 1 month ago 7
jQuery Question

Re-arrange an HTML table with jQuery based on a given array of row IDs

I have an HTML table in which each data row has a unique

id
attribute. I am writing a script that polls a server for data and uses the results it gets to re-sort the table. From the server, I receive an array like this:

var order_arr = [6, 4, 2, 1, 5, 3]


Which I want to use to visually re-sort some table data like this:

<tr id="user-1">...</tr>
<tr id="user-2">...</tr>
<tr id="user-3">...</tr>
<tr id="user-4">...</tr>
<tr id="user-5">...</tr>
<tr id="user-6">...</tr>


So that it appears to the user like this:

<tr id="user-6">...</tr>
<tr id="user-4">...</tr>
<tr id="user-2">...</tr>
<tr id="user-1">...</tr>
<tr id="user-5">...</tr>
<tr id="user-3">...</tr>


I wrote some jQuery code on jsFiddle to do this, but I don't know if it's the best technique. It fetches the array of
<tr>
elements and sorts them based on the corresponding index of each row's ID. It ends with a
.html()
call that just replaces the whole table body content.

So.. tl;dr:


  1. Is this code the best way to visually
    re-sort an HTML table given an array
    holding the desired order of row
    IDs?

  2. How can I make this animated? I
    was thinking I could write this as a
    CSS hack instead, in which each
    table row has an absolute position
    and I could just run
    .animate()

    after calculating which position
    each row should hold. Thoughts vs.
    my current code?


Answer

The best solution I could find which kept the original functionality and added animation was with CSS. Here's the relevant JS:

function sort(order_arr) {
    var top = 0;    
    $.each(order_arr, function(idx, val) {
        var el = $('tbody tr#user-' + val);

        el.animate({
            position: 'absolute',
            top: top + 'px'
        }, 400);
        top += el.outerHeight();
    });
}

Demo on jsFiddle