Table sorting using JavaScript and javascript table sorting
Table sorter includes JavaScript and a bit of CSS, which enables the original html table to be sorted by data values in each column.
Performance Requirements
JS Code:
"Use strict"; window. onload = function () {var tables = getAllTables (); makeAllTablesSortalbe (tables) ;}; // use the following two rows for embedding .. // 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]);} // makes the list sorted. 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); // locate the index value for (var j = 0; j <th. length; j ++) {if (this = th [j]) index = j;} sortByTh (table, index, this. className) ;}}// change the style function changeStyle (th, t) {for (var I = 0; I <th. length; I ++) {if (th [I] = t) {if (th [I]. className. indexOf ("descen D ")! =-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", "") ;}}// sorting 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 if (action = 'scend') {return. cells [index]. innerHTML <= B. cells [index]. innerHTML;} else {// return a in descending order. 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");}