Sortable

a (tiny) vanilla javascript table sorter

Sort-a-what?

SortableUM makes any table with class="sortable", er, sortable. Sort-able. Able-to-be-sorted. That is the user can click on a table header and change the sorting of the table rows.

Just include the JavaScript and it will work. No function calls needed, all is done with an eventListener. (The CSS is not strictly needed, but makes it pretty and user friendly)

You can download the (tiny) package from Github.

An example

Role Name
Master Rick
Servant Morty

This small masterpiece is generated thusly:


<table class="sortable">
<thead>
  <tr>
    <th>Role</th>
    <th>Name</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Master</td>
    <td>Rick</td>
  </tr>
  <tr>
    <td>Servant</td>
    <td><a href="javascript:alert('Morty');">Morty</a></td>
  </tr>
</tbody>
</table>
<link href="sortable.css" rel="stylesheet">
<script src="sortable.js"></script>

There is also the Bigger Example.

Factoids

Note!

The table needs to have both thead and tbody. (tfoot is not involved.)

SortableUM WILL remove EventListeners - not inline JS - from the table rows. There is no way to prevent this. Try attaching them to the table element instead, then use e.target to find out where the click came from.

Instead of:


document.getElementById('[TD]-id')
    .addEventListener('click',function(e){
    var td = this;
    //...do stuff

});
            

Do this:


document.getElementById('[TABLE]-id')
    .addEventListener('click',function(e){
    var td = e.target;
    //...do stuff

});

            

I find this later approach to be generally more useful. It's also a good idea not to use "this" unless you must, due to its ambiguity.

(Un)License

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org