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:
- Is this code the best way to visually re-sort an HTML table given an array holding the desired order of row IDs?
- 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?