About this snippet

Organize large datasets with this sortable table. Clicking any column header reorders the rows alphabetically or numerically, which makes finding specific information much faster for your users.

Size
2.2 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
481
<div class="table-wrap">
  <table id="sortable">
    <thead>
      <tr>
        <th onclick="sortTable(0)">Name &#8645;</th>
        <th onclick="sortTable(1)">Role &#8645;</th>
        <th onclick="sortTable(2)">Age &#8645;</th>
      </tr>
    </thead>
    <tbody>
      <tr><td>Zack</td><td>Designer</td><td>24</td></tr>
      <tr><td>Alice</td><td>Manager</td><td>30</td></tr>
      <tr><td>John</td><td>Developer</td><td>28</td></tr>
      <tr><td>Bob</td><td>Designer</td><td>22</td></tr>
    </tbody>
  </table>
</div>
.table-wrap {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  max-width: 600px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
}
table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
}
th {
  background: #f9fafb;
  padding: 15px;
  text-align: left;
  cursor: pointer;
  user-select: none;
  color: #1f2937;
  font-weight: 600;
}
th:hover {
  background: #f3f4f6;
}
td {
  padding: 15px;
  border-top: 1px solid #e5e7eb;
  color: #4b5563;
}
function sortTable(n) {
  const table = document.getElementById("sortable");
  let rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  switching = true;
  dir = "asc";
  
  while (switching) {
    switching = false;
    rows = table.rows;
    
    for (i = 1; i < (rows.length - 1); i++) {
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      
      const xContent = isNaN(x.innerHTML) ? x.innerHTML.toLowerCase() : Number(x.innerHTML);
      const yContent = isNaN(y.innerHTML) ? y.innerHTML.toLowerCase() : Number(y.innerHTML);

      if (dir == "asc") {
        if (xContent > yContent) {
          shouldSwitch = true;
          break;
        }
      } else if (dir == "desc") {
        if (xContent < yContent) {
          shouldSwitch = true;
          break;
        }
      }
    }
    
    if (shouldSwitch) {
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      switchcount++;
    } else {
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save