Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / JavaScript Sort Table on Header Click

JavaScript Sort Table on Header Click

January 22, 2024January 11, 2024 by Asif Mughal
JavaScript Sort Table on Header Click
Share This:
Code Snippet:Pure JavaScript Sortable Table
Author: Murat DoÄŸan
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 7,315
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code snippet helps you to sort the HTML table on header click. It stores the table data in const objects and renders that to the HTML table dynamically. In order to sort the table columns, it uses the JavaScript array sort method.

How to Create JavaScript Sort Table on Header Click

1. First of all, create the HTML table element with a unique id and place “th” element with the data-filter-value attribute. Similarly, define data-filter values as follows:

 <table id="squadTable" class="table table-dark table-striped">
    <thead>
        <tr>
            <th data-filter-value="no" class="active">No <i class="fa fa-sort"></i></th>
            <th>Adı</th>
            <th>Pozisyonu</th>
            <th data-filter-value="dateOfBirth">YaÅŸ <i class="fa fa-sort"></i></th>
            <th data-filter-value="match">Maç <i class="fa fa-sort"></i></th>
            <th data-filter-value="goal">Gol <i class="fa fa-sort"></i></th>
            <th data-filter-value="assist">AST <i class="fa fa-sort"></i></th>
            <th data-filter-value="yellowCard">SK <i class="fa fa-sort"></i></th>
            <th data-filter-value="doubleYellowCard">ÇSK <i class="fa fa-sort"></i></th>
            <th data-filter-value="redCard">KK <i class="fa fa-sort"></i></th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

2. After that, define the following CSS style for the table header “th” element:

th[data-filter-value] {
  cursor: pointer;
}
th.active {
  color: red;
}

3. Now, add the following JS table sort code to your project. In this code, place the table data inside the JavaScript array of objects.

const data = [{
  "id": "1233213",
  "no": 17,
  "fullName": "Murat DoÄŸan",
  "position": "CMD",
  "age": 29,
  "dateOfBirth": "1985-08-06T00:00:00",
  "match": 12,
  "time": 1080,
  "goal": 12,
  "assist": 4,
  "yellowCard": 3,
  "doubleYellowCard": 0,
  "redCard": 2 },
{
  "id": "41233213",
  "no": 58,
  "fullName": "Lorem Ipsum",
  "position": "GK",
  "age": 28, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 34,
  "time": 3400,
  "goal": 1,
  "assist": 17,
  "yellowCard": 8,
  "doubleYellowCard": 3,
  "redCard": 5 },
{
  "id": "51233213",
  "no": 18,
  "fullName": "Dolor Sit",
  "position": "ST",
  "age": 33, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 5,
  "time": 120,
  "goal": 1,
  "assist": 2,
  "yellowCard": 5,
  "doubleYellowCard": 1,
  "redCard": 4 },
{
  "id": "61233213",
  "no": 27,
  "fullName": "Amet Dolor",
  "position": "DL",
  "age": 18, "dateOfBirth": "1985-08-06T00:00:00",
  "match": 2,
  "time": 12,
  "goal": 0,
  "assist": 1,
  "yellowCard": 3,
  "doubleYellowCard": 4,
  "redCard": 5 }];


let currentFilter = "",
prevFilter = "",
orderAsc = true;

const toggleOrder = () => {
  if (currentFilter === prevFilter) {
    orderAsc = !orderAsc;
  } else {
    orderAsc = true;
  }
};

const calcAge = birthDate => {
  let bDate = new Date(birthDate),
  bDateYear = bDate.getUTCFullYear(),
  now = new Date().getFullYear();

  return now - bDateYear;
};

const sortTable = (array, sortKey) => {
  return array.sort((a, b) => {
    let x = a[sortKey],
    y = b[sortKey];

    return orderAsc ? x - y : y - x;
  });
};

const renderTable = tableData => {
  return `${tableData.map(item => {
    if (item.dateOfBirth.length > 2) {
      item.dateOfBirth = calcAge(item.dateOfBirth);
    }
    return (
      `<tr>
                        <td>${item.no}</td>
                        <td>${item.fullName}</td>
                        <td>${item.position}</td>
                        <td>${item.dateOfBirth}</td>
                        <td>${item.match}</td>
                        <td>${item.goal}</td>
                        <td>${item.assist}</td>
                        <td>${item.yellowCard}</td>
                        <td>${item.doubleYellowCard}</td>
                        <td>${item.redCard}</td>
                    </tr>`);

  }).join('')}`;
};

const appendTable = (table, destination) => {
  document.querySelector(destination).innerHTML = table;
};

const handleSortClick = () => {
  const filters = document.querySelectorAll('#squadTable th');

  Array.prototype.forEach.call(filters, filter => {
    filter.addEventListener("click", () => {
      if (!filter.dataset.filterValue) return false;

      Array.prototype.forEach.call(filters, filter => {
        filter.classList.remove('active');
      });
      filter.classList.add('active');
      currentFilter = filter.dataset.filterValue;
      toggleOrder();
      init();
    });
  });
};

const init = () => {
  let newTableData = sortTable(data, currentFilter),
  tableOutput = renderTable(newTableData);

  appendTable(tableOutput, '#squadTable tbody');

  prevFilter = currentFilter;
};

init();
handleSortClick();

That’s all! hopefully, you have successfully integrated this JavaScript sort table code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Similar Code Snippets:

  • JavaScript Button Ripple Effect Onclick

    JavaScript Button Ripple Effect Onclick

  • Create Scratch Card using JavaScript & HTML5 Canvas

    Create Scratch Card using JavaScript & HTML5 Canvas

  • JavaScript Single Select Dropdown

    JavaScript Single Select Dropdown

  • JavaScript Timer Countdown Minutes Seconds

    JavaScript Timer Countdown Minutes Seconds

  • To Do List Project in JavaScript

    To Do List Project in JavaScript

  • JavaScript Crop Image and Save

    JavaScript Crop Image Before Upload 100% Working

  • JavaScript Unit Converter Source Code

    JavaScript Unit Converter Source Code

  • Collapsible Timeline Using CSS3 and Vanilla JS

    Collapsible Timeline Using CSS3 and Vanilla JS

  • Fadein And Fadeout in JavaScript

    Fadein And Fadeout in JavaScript

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript
JavaScript Slide Up & Down div From Bottom
Bootstrap 4 Custom Alert & Confirm Popup with jQuery

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,408 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,942 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,950 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,360 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,039 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,105 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,393 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,390 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,150 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,202 views

Advertisement

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

Please Rel0ad/PressF5 this page if you can't click the download/preview link

F5
X