JavaScript implementation of table sorting

Keywords: Javascript xml

Table sorter includes JavaScript and a little CSS, which can make the original html table be able to sort each row according to the data value of each column.

Effect

  1. Click in any column in the header, and the following lines will be sorted in ascending order according to the column value
    Order by string comparison
  2. Click the column again and change to descending order
  3. Click other columns to reorder by the values of other columns
  4. Note that when sorting, the background color of column odd and even rows should be odd white and even light gray

Requirement

  1. The original html cannot be changed, only js and css files can be added
  2. No class library can be used, only native DOM API can be used
  3. JavaScript must be modularized. The call entry of JS must follow the following figure:

sorter.js:

"use strict";

window.onload = function () {
    var tables = getAllTables();
    makeAllTablesSortalbe(tables);
};

//For embedding, use the following two lines
// var tables = getAllTables();
// makeAllTablesSortalbe(tables);
function getAllTables() {
    return document.getElementsByTagName("table");
}


function makeAllTablesSortalbe(tables) {
    for (var i = 0; i < tables.length; i++)
        makeSort(tables[i]);
}

//Make the list sortable
function makeSort(table) {
    var th = table.getElementsByTagName("th");
    for (var i = 0; i < th.length; i++) {
        //Bind button event
        th[i].onclick = function () {
            var index = 0;
            changeStyle(th, this);
            //Find index value
            for (var j = 0; j < th.length; j++) {
                if (this == th[j])
                    index = j;
            }
            sortByTh(table, index, this.className);
        };
    }
}

//Changing styles
function changeStyle(th, t) {
    for (var i = 0; i < th.length; i++) {

        if (th[i] == t) {

            if (th[i].className.indexOf("descend") != -1 )
                th[i].className = th[i].className.replace("descend", "ascend");
            else if (th[i].className.indexOf("ascend") != -1 )
                th[i].className = th[i].className.replace("ascend", "descend");
            else
                th[i].className += " descend";

        } else {
            th[i].className = th[i].className.replace("descend", "");
            th[i].className = th[i].className.replace("ascend", "");
        }
    }
}

//sort
function sortByTh(table, index, className) {
    var action = className.indexOf("descend") != -1 ? "descend" : "ascend";
    var array = [];
    for (var i = 1; i < table.getElementsByTagName("tr").length; i++) {
        array[i-1] = table.getElementsByTagName("tr")[i];
    }
    array.sort(function (a, b) {
        //Ascending order
        if (action == 'descend') {
            return a.cells[index].innerHTML <= b.cells[index].innerHTML;
        } else {
        //Descending order
            return a.cells[index].innerHTML >= b.cells[index].innerHTML;
        }
    });

    for (var i = 0; i < array.length; i++)
        table.getElementsByTagName("tbody")[0].appendChild(array[i]);
}

CSS:

    border: 1px solid gray;
    margin: 0;
    padding: 3px;
    border-collapse: collapse;
}

tr:nth-child(even),tr:hover {
    background-color: #DEDEDE;
}

th {
    text-align: left;
    background-color: #041A7F;
    color: white;
    font-weight:  bold;
    padding-right:16px;
}

.ascend, .descend {
    background-color: #A4B0FC;
    background-position: right;
    background-repeat: no-repeat;
}

.ascend {
    background-image: url("ascend.png");
}

.descend {
    background-image: url("descend.png");
}

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sortable table</title>
    <link rel="stylesheet" type="text/css" href="sorter.css" />
    <script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<h1>Sortable table</h1>

<h2>To-Do</h2>

<table id="todo">
    <thead>
        <tr>
            <th>What?</th>
            <th>When?</th>
            <th>Location</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Paris Web 2007</td>
            <td>2007-11-15</td>
            <td>IBM La Defense / INSIA</td>
        </tr>
        <tr class="alternate">
            <td>Paris On Rails 2007</td>
            <td>2007-12-10</td>
            <td>Cite des Sciences</td>
        </tr>
        <tr>
            <td>Burger Quiz party</td>
            <td>2007-04-14</td>
            <td>Volta</td>
        </tr>
    </tbody>
</table>

<h2>Staff</h2>

<table id="staff">
    <thead>
        <tr>
            <th>First name</th>
            <th>Last name</th>
            <th>Latest checkin</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Richard</td>
            <td>Piacentini</td>
            <td>2007-03-27</td>
        </tr>
        <tr class="alternate">
            <td>Eric</td>
            <td>Daspet</td>
            <td>2007-03-28</td>
        </tr>
        <tr>
            <td>Aurore</td>
            <td>Jaballah</td>
            <td>2007-03-15</td>
        </tr>
    </tbody>
</table>

</body>
</html>

sorter.css

table, tr *{
    border: 1px solid gray;
    margin: 0;
    padding: 3px;
    border-collapse: collapse;
}

tr:nth-child(even),tr:hover {
    background-color: #DEDEDE;
}

th {
    text-align: left;
    background-color: #041A7F;
    color: white;
    font-weight:  bold;
    padding-right:16px;
}

.ascend, .descend {
    background-color: #A4B0FC;
    background-position: right;
    background-repeat: no-repeat;
}

.ascend {
    background-image: url("ascend.png");
}

.descend {
    background-image: url("descend.png");
}

Posted by dylan001 on Fri, 08 Nov 2019 06:54:53 -0800