Sorting Table Data
Because HTML tables are static, you cannot sort them using HTML or CSS alone. To sort table data, you must use a small amount of JavaScript inside a script element.
When you have a large dataset, allowing users to sort the table (e.g., alphabetically by name, or numerically by price) is a huge usability improvement. The most common way to do this is by making the table's header cells clickable.
Setting Up the HTML
First, you need to prepare your table. You should give your table an id so the JavaScript can easily find it. Then, add an onclick attribute to your th elements to trigger the sorting function:
The JavaScript Function
Next, we add the logic. The following script looks at all the rows inside the tbody, compares the text of two adjacent cells in the chosen column, and switches their positions if they represent a wrong alphabetical order. It does this repeatedly until the whole table is sorted:
Full Working Example
Try clicking on the headers in the example below to see the JavaScript sort function in action. Notice how clicking the same header a second time reverses the sorting direction:
Tip: Better Cursors
When you make an element clickable that isn't a link or a button, you should change the mouse cursor so the user knows they can click it. You can do this in your CSS by targeting the headers: th { cursor: pointer; }.