2

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?
3
  • Does the table actually need to be sorted in the dom or just visually sorted? Commented Mar 2, 2011 at 0:16
  • It could be just visually sorted, that's fine. That's what I was thinking with my CSS animation idea. Sorry, I realize now that explaining it that way might've given the wrong message. Commented Mar 2, 2011 at 0:25
  • Here's my CSS sort idea: jsfiddle.net/hans/6qVf5/3 Commented Mar 2, 2011 at 1:05

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.