< BACK TO COMPONENTS

How to Sort HTML Table by Header Click | Sorting Data Tables

Faraz

By Faraz -

Learn how to sort your HTML tables by clicking on the headers. This tutorial covers everything you need to know about adding sorting functionality to your data tables.


how to sort rows in a table with headers using javascript.png

Sorting tables is always a rather difficult problem to solve. There are a lot of interactions to track, a lot of DOM mutations to implement, and even complex sorting algorithms. This is just one of the tough challenges. Right?.


Sorting HTML tables is a useful feature that can improve the user experience of web applications. In this blog post, we'll be focusing on sorting tables by header click using JavaScript. By the end of this post, you'll be able to add sorting functionality to your HTML tables, allowing users to sort data in ascending or descending order based on the column they click on.


Instead of pulling from external libraries, Let's start making a sortable table using HTML, CSS, and JavaScript by ourselves.


Understanding HTML Tables


HTML tables are used to display data in rows and columns. They are often used to present data in a structured and organized manner, making it easy to read and understand. In an HTML table, each row represents a record and each column represents a field of that record. Tables can also be used to present data in a searchable and filterable format.


HTML tables are used to display data in rows and columns. They are often used to present data in a structured and organized manner, making it easy to read and understand. In an HTML table, each row represents a record and each column represents a field of that record. Tables can also be used to present data in a searchable and filterable format.


Join My Telegram Channel to Download the Project: Click Here


Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our table.


The below code represents an HTML document that includes a table with two columns: "Name" and "Country". The table contains data about several companies, including their names and the countries in which they are located.


The first row of the table contains the column headers, which are formatted using the "th" tag. Each header has an "onclick" attribute that calls a JavaScript function called "sortTable" when clicked. This function is intended to sort the table by the corresponding column when the header is clicked.


The remaining rows of the table represent the data for each company, with each row containing two "td" tags for the name and country columns, respectively.


At the bottom of the HTML document, there is a script tag that references a JavaScript file called "script.js". This file presumably contains the implementation for the "sortTable" function mentioned earlier.


After creating the files just paste the below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


This is the basic structure of our table using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the table is in place, the next step is to add styling to the table using CSS.


Next, we will create our CSS file. We will use some basic CSS rules in this file to style our table.


body{ background-color: rgb(211, 226, 216); }: This rule sets the background color of the web page to a shade of light green.


table { border-spacing: 0; width: 80%; border: 1px solid #dddd; }: This rule applies to all table elements and sets their border spacing to 0, their width to 80% of the parent element, and their border to a solid gray color.


th, td { text-align: left; padding: 15px; }: This rule applies to all th and td elements and sets their text alignment to left and their padding to 15 pixels on all sides.


tr:nth-child(even) { background-color: rgb(153, 153, 197); }: This rule applies to every even-numbered tr element in a table and sets its background color to a shade of light purple. This creates a striped effect for the rows in the table, which can help improve readability.


This will give our table an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body{
  background-color: rgb(211, 226, 216);
}

table {
  border-spacing: 0;
  width: 80%;
  border: 1px solid #dddd;
}

th,
td {
  text-align: left;
  padding: 15px;
}

tr:nth-child(even) {
  background-color: rgb(153, 153, 197);
} 

Step 3 (JavaScript Code):

Finally, we need to implement a table sort functionality for an HTML table in JavaScript.


Here is an explanation of each section of the code:


let table; table = document.getElementById('table');: This code retrieves the HTML table element by its id attribute, and assigns it to the table variable.


let rows, i, x, y, count = 0; let switching = true;: This code initializes several variables used in the sorting algorithm, including rows which stores all the rows in the table, i which is an iterator used to loop through the rows, x and y which store the values of the two elements being compared, and count which keeps track of the number of switches made.


let direction = 'ascending';: This code initializes the direction of sorting as ascending, meaning that the table will be sorted in increasing order.


while (switching) {...}: This code initiates a while loop that will run as long as the switching variable is true. This variable is set to true initially, so the loop will run at least once.


switching = false; let rows = table.rows;: These lines set the switching variable to false and retrieve the rows of the table.


for (i = 1; i < rows.length - 1; i++) {...}: This code loops through each row of the table, skipping the first row since it contains the table header.


var Switch = false;: This line initializes a variable Switch which will be used to mark whether the current row needs to be switched with the next row.


x = rows[i].getElementsByTagName('TD')[n]; y = rows[i + 1].getElementsByTagName('TD')[n];: These lines retrieve the values of the two elements being compared, using the column index n.


if (direction == 'ascending') {...}: This code checks if the table is being sorted in ascending order. If so, it checks if the value of x is greater than the value of y. If it is, it marks the Switch variable as true, indicating that the rows need to be switched.


else if (direction == 'descending') {...}: If the table is being sorted in descending order, this code checks if the value of x is less than the value of y. If it is, it marks the Switch variable as true.


if (Switch) {...}: If the Switch variable is true, this code switches the two rows and marks the switching variable as true. It also increments the count variable to keep track of the number of switches made.


else {...}: If the Switch variable is false, this code checks if count is 0 and the table is being sorted in ascending order. If so, it sets the direction of sorting to descending and marks the switching variable as true.


In summary, this function provides a basic implementation of a sorting algorithm for a table that can sort on any column in ascending and descending orders. The implementation uses a simple bubble-sort algorithm to compare each element with its neighbor, and swaps them if necessary.


Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

// JavaScript program to illustrate
// Table sort for both columns and both directions.
function sortTable(n) {
  let table;
  table = document.getElementById('table');
  let rows,
    i,
    x,
    y,
    count = 0;
  let switching = true;

  // Order is set as ascending
  let direction = 'ascending';

  // Run loop until no switching is needed
  while (switching) {
    switching = false;
    let rows = table.rows;

    //Loop to go through all rows
    for (i = 1; i < rows.length - 1; i++) {
      var Switch = false;

      // Fetch 2 elements that need to be compared
      x = rows[i].getElementsByTagName('TD')[n];
      y = rows[i + 1].getElementsByTagName('TD')[n];

      // Check the direction of order
      if (direction == 'ascending') {
        // Check if 2 rows need to be switched
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          // If yes, mark Switch as needed and break loop
          Switch = true;
          break;
        }
      } else if (direction == 'descending') {
        // Check direction
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          // If yes, mark Switch as needed and break loop
          Switch = true;
          break;
        }
      }
    }
    if (Switch) {
      // Function to switch rows and mark switch as completed
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;

      // Increase count for each switch
      count++;
    } else {
      // Run while loop again for descending order
      if (count == 0 && direction == 'ascending') {
        direction = 'descending';
        switching = true;
      }
    }
  }
}

Final Output:

how to sort rows in a table with headers using javascript.gif

Conclusion:

By following these steps, you can easily add sorting functionality to an HTML table using JavaScript. This allows users to sort the data in a specific column in ascending or descending order, making it easier to find the information they need.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post