In this tutorial, you can learn to create a simple Sortable HTML Table Data Order using only Pure JavaScrtip. This tutorial aims to provide students and beginners with a reference for learning to build an interactive Web application or website component. Here, I will be providing source code that demonstrates the creation of a simple HTML Table with sorting features and functionalities.
A sortable HTML Table is one of the most common and implemented components in web applications or websites. It is data that is shown in a table view and each column can be sorted in ascending or descending order. Ordering or Sorting column data are often triggered when the user clicks the column header.
Nowadays, there are a lot of JS libraries that allow the developer to initialize or implement a sorting feature to an HTML Table. Here, I will show you how to create a Sortable feature for the HTML Table column.
Sortable HTML Table can be achieved easily using Pure JavaScript without using other JS libraries. JavaScript comes with multiple useful built-in methods, functions, event listeners, and Web APIs and some of these became handy to build a sortable HTML table. We can simply create the HTML Table with the data we want to display and design it with CSS for how we wanted to the table to look. Then, we can initialize the sorting features using JavaScrtip. Check out the web application scripts that I provided below to know more and have a better idea of how to create a simple sortable HTML Table.
The following scripts result in a simple web page that contains static data. The data are shown in a table view where each column has a sortable link on the header that allows the users to sort the table data in ascending or descending order.
Here's the HTML file script known as index.html. The file contains the Page Layout and Table elements.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> </head> <body> <div class="container"> <hr id="title_hr"> <div id="sortable-table-wrapper"> <table id="sortable-tbl"> <thead> <tr> </tr> </thead> <tbody> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> <tr> </tr> </tbody> </table> </div> </div> </body> </html>
Next, here is the CSS file script known as style.css. This file contains the stylesheet codes for the page interface and table elements designs.
@import url('https://fonts.googleapis.com/css2?family=Dongle:wght@300;400;700&family=Roboto+Mono:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,100;1,200;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet'); *{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Dongle', sans-serif; font-family: 'Roboto Mono', monospace; } ::selection{ color: #fff; background: #4db2ec; } body{ display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #4facfe; background-image: linear-gradient(to right, #4facfe 0%, #00f2fe 100%); padding: 2em 0; } #page-title{ color: #fff; text-align: center; font-weight: 500; text-shadow: 0px 0px 15px #0000003a; } #title_hr{ width:60px; border: 2px solid #ffffff; margin: .35em auto; } @media (min-width: 780px){ #page-title{ width: 780px; } } /* Table Wrapper */ #sortable-table-wrapper{ width: 700px; background-color: #fff; border: 1px solid #d1d1d1; padding: 1em .75em; margin: 1em auto; border-radius: 5px; box-shadow: 1px 1px 10px #00000046; overflow-y:auto; } /* Table */ #sortable-tbl{ border-collapse:collapse; width: 100%; } /* Table Cell */ #sortable-tbl th,#sortable-tbl td{ border: 1px solid #cfcfcf; padding: .5em .35em; } /* Sortable Table Sort Link */ .tableSortableClass a.tbl-sort-link { width: 100%; display: flex; justify-content: space-between; align-items: center; cursor: pointer; } /* Sortable Table Sort Link Icon Holder */ .tableSortableClass a.tbl-sort-link span.tbl-sort-order { display: flex; align-items: center; justify-content: center; } .tableSortableClass a.tbl-sort-link span.tbl-sort-order>span{ color: #afafaf; font-size: 1.1rem; width: 13px; } .tableSortableClass a.tbl-sort-link span.tbl-sort-order>span.tbl-sort-order-desc{ rotate: 180deg; } .tableSortableClass a.tbl-sort-link[data-sort="true"][data-order="asc"] span.tbl-sort-order>span:nth-child(1){ color:#404040; } .tableSortableClass a.tbl-sort-link[data-sort="true"][data-order="desc"] span.tbl-sort-order>span:nth-child(2){ color:#404040; }
Lastly, here is the JavaScript file script known as script.js. The file contains the JS codes that initialize the Sorting and makes it functional.
// HTML Table Sorting Class class TableSorting { Table; col = 1; sortOrder = 'asc'; // Contructor Intitalize Default constructor(table, options = {}){ // Set Table Element this.Table = table // Set Default Sorting Column if(!!options.col){ this.col = options.col } // Set Default Sorting Order if(!!options.sortOrder){ this.sortOrder = options.sortOrder } // Add Sort Link to table header columns this.theadAddSort() } theadAddSort(){ // Adding Table Sort Class name for the design this.Table.classList.add('tableSortableClass') // Selecting the first thead row var theadRow = this.Table.querySelector('thead tr:nth-child(1)') // Add Column sort link theadRow.querySelectorAll('th').forEach((el, idx) =>{ // Get the column Text var thTxt = el.innerText // Increment Index to get the node child index idx += 1; // Creating a New Element as the sort link of the column var newContent = document.createElement('a') // adding class to the sort link newContent.classList.add('tbl-sort-link') // Sort Link Content newContent.innerHTML = `<span class='tbl-sort-title'>${thTxt}</span> <span class="tbl-sort-order"> <span class="tbl-sort-order-asc material-symbols-outlined">straight</span> <span class="tbl-sort-order-desc material-symbols-outlined">straight</span></span>`; // Clean the Column Content Temporarily el.innerHTML = ''; // Inserting or Adding the New Column content to current column el.appendChild(newContent) // Sort Table Data this.orderData() }) // Updating Active Sorting Icon this.updateSortIcons() // Trigger for changing the table sort order this.changeSort() } updateSortIcons(){ // Select All the thead table row first child's table cel var theadRow = this.Table.querySelector('thead tr:nth-child(1)') theadRow.querySelectorAll('th').forEach((el, idx) =>{ idx++; // add dataset to the sort link if the current sort column and this column index is equal if(idx == this.col){ el.querySelector('a.tbl-sort-link').dataset.sort = 'true' el.querySelector('a.tbl-sort-link').dataset.order = this.sortOrder } }) } orderData(){ // variable to identify if there's data needed to reorder var hasSort = false; // Elements to reorder var reorder = []; // Selecting all the table body rows var trs = this.Table.querySelectorAll('tbody tr') trs.forEach((el, idx) => { // Check if this element has a next element, continue to the process if it does if(el.nextElementSibling != null){ if(this.sortOrder == `asc`){ // Checking the Data Order if descending. If yes, store elements to reorder array if(el.querySelector(`td:nth-child(${this.col})`).innerText.toLowerCase() > el.nextElementSibling.querySelector(`td:nth-child(${this.col})`).innerText.toLowerCase()){ hasSort = true reorder.push({eltoTransfer:el.nextElementSibling, transferBefore: el}) } }else{ // Checking the Data Order if ascending. If yes, store elements to reorder array if(el.querySelector(`td:nth-child(${this.col})`).innerText.toLowerCase() < el.nextElementSibling.querySelector(`td:nth-child(${this.col})`).innerText.toLowerCase()){ hasSort = true reorder.push({eltoTransfer:el.nextElementSibling, transferBefore: el}) } } } }) if(hasSort){ // If there's data to reorder execute the transfer of elements reorder.forEach(data => { data.eltoTransfer.parentNode.insertBefore(data.eltoTransfer, data.transferBefore) }) // Re-Check Order this.orderData() } } changeSort(){ // Select All Sort Order Link this.Table.querySelectorAll('a.tbl-sort-link').forEach((el, idx)=>{ // Iterate Index to get element child index idx++; // Add Click Event Listener to each sort link el.addEventListener('click', e => { // prevent default if link is clicked e.preventDefault() // getting the current element var currentCol = this.col if(currentCol == idx){ // If current column and this element index is still the same, update only the sort order if(this.sortOrder == 'asc') this.sortOrder = 'desc'; else this.sortOrder = 'asc'; }else{ // If the current Column is different to this element index // set sorting order to asc by default this.sortOrder = `asc` // Getting the current sort order link element var currentColOrder = this.Table.querySelector(`a.tbl-sort-link[data-sort='true']`) // Remove the sort ordering datasets to the current sort order link if(!!currentColOrder.dataset.sort) delete currentColOrder.dataset.sort; if(!!currentColOrder.dataset.order) delete currentColOrder.dataset.order; // Update the sort column this.col = idx } // Update Sort Icons this.updateSortIcons() // Update Table sort order this.orderData() }) }) } } // Select Table Element to Sort const table = document.getElementById('sortable-tbl') // Initialize Sortaing Table const sortTable = new TableSorting(table, {col:2, sortOrder: 'asc'})
Here are some snapshots of the overall result of the file scripts that I provided.
There you go! I have provided also the complete source code zip file of the web application scripts that I provided on this website and it is free to download. The download button is located below this tutorial's content. Feel free to download and modify the source code the way you wanted to meet your own requirements and enhance your programming capabilities.
That's it! I hope this Create a Sortable HTML Table using Pure JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web application projects.
Explore more on this website for more Tutorials and Free Source Codes.