How to Make Any Table on Your Website Sortable Without Any Plugin

Adding sorting functionality to tables on your website can significantly enhance the user experience, allowing visitors to interact with and analyze data more efficiently. While there are numerous plugins available for this purpose, you can achieve table sorting without relying on external plugins. In this guide, we’ll explore a simple JavaScript solution that can make any table on your website sortable with just a few lines of code.

Prerequisites

Before we begin, ensure you have a basic understanding of HTML, CSS, and JavaScript.

The HTML Structure

Let’s assume you have a table in your HTML document. For demonstration purposes, we’ll use a sample table representing city data:

<table id="sortableTable">
  <!-- Table header -->
  <thead>
    <tr>
      <th>City</th>
      <th>Population</th>
      <th>Area (km²)</th>
    </tr>
  </thead>
  <!-- Table body -->
  <tbody>
    <tr>
      <td>New York</td>
      <td>8.4 million</td>
      <td>468.9</td>
    </tr>
    <!-- Add more rows as needed -->
  </tbody>
</table>

The JavaScript Magic

Now, let’s add the Stylesheets and JavaScript code to make the table sortable. This script dynamically adds sorting functionality to all tables within the page. Just copy and paste the code such that its available in everypage.

<style>
  th, td {
    padding: 10px;
    text-align: left;
    border: 1px solid #ddd;
    position: relative;
    cursor: pointer;
  }

  .sortable-icon {
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translateY(-50%);
  }

  .asc .sortable-icon::before {
    content: '↑';
    color: #e1e4e7; /* Highlight color for ascending */
  }

  .desc .sortable-icon::before {
    content: '↓';
    color: #dae7f4; /* Highlight color for descending */
  }
</style>

<script>
  // Function to parse table cell content and convert to numeric value
  function parseTableCell(cell) {
    var cellContent = cell.textContent || cell.innerText;
    // Remove commas from the number string
    var numericValue = parseFloat(cellContent.replace(/,/g, ""));
    return isNaN(numericValue) ? cellContent.toLowerCase() : numericValue;
  }

  // Function to sort the table
  function sortTable(columnIndex, table) {
    var rows, switching, i, x, y, shouldSwitch;
    switching = true;
    var direction = table.getAttribute("data-sort-direction") === "asc" ? "desc" : "asc";

    while (switching) {
      switching = false;
      rows = table.getElementsByTagName("tr");

      for (i = 1; i < rows.length - 1; i++) {
        shouldSwitch = false;

        x = rows[i].getElementsByTagName("td")[columnIndex];
        y = rows[i + 1].getElementsByTagName("td")[columnIndex];

        // Compare values based on data type
        x = parseTableCell(x);
        y = parseTableCell(y);

        if ((direction === 'asc' && x > y) || (direction === 'desc' && x < y)) {
          shouldSwitch = true;
          break;
        }
      }

      if (shouldSwitch) {
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
      }
    }

    // Toggle sort direction and update icon
    table.setAttribute("data-sort-direction", direction);
    updateSortIcons(table, columnIndex, direction);
  }

  // Function to check if a value is numeric
  function isNumeric(value) {
    return !isNaN(parseFloat(value)) && isFinite(value);
  }

  // Function to update sort icons
  function updateSortIcons(table, columnIndex, direction) {
    var headers = table.getElementsByTagName("th");

    // Remove existing icons
    Array.from(headers).forEach(function (header) {
      header.classList.remove('asc', 'desc');
    });

    // Add icon to the clicked header
    headers[columnIndex].classList.add(direction);
  }

  // Function to make tables sortable
  function makeTablesSortable() {
    var tables = document.querySelectorAll("table");

    tables.forEach(function (table) {
      table.setAttribute("data-sort-direction", "asc");

      var headers = table.getElementsByTagName("th");

      Array.from(headers).forEach(function (header, index) {
        header.onclick = function () {
          sortTable(index, table);
        };
        header.innerHTML += '<span class="sortable-icon"></span>';
      });
    });
  }

  // Make all tables on the page sortable
  makeTablesSortable();
</script>


Conclusion

By following these steps, you can make any table on your website sortable without relying on external plugins. This approach provides a lightweight and customizable solution, ensuring that your tables remain user-friendly and interactive.

Feel free to customize the code according to your specific requirements and integrate it seamlessly into your website.

Happy coding!