Click on the table headings to sort the table.
Id |
Last Name |
First Name |
Postal Code |
City |
Age |
1 |
Mueller |
Albert |
31245 |
Kassel |
60 |
2 |
Schmidt |
Hubert |
12456 |
Baunatal |
30 |
3 |
Lehmann |
Dirk |
90123 |
Nuernberg |
25 |
4 |
Kaiser |
Michael |
23456 |
Dortmund |
29 |
5 |
Rudoplh |
Peter |
87654 |
Essen |
43 |
// functions
// Get all tr-elems from document and connect hover handling function
function installHoverHandlers()
{
var rows = document.getElementsByTagName('tr');
for(i=0; i<rows.length; i++)
{
rows[i].onmouseover = createElemBgColorHandler(rows[i], '#EEEEEE');
rows[i].onmouseout = createElemBgColorHandler(rows[i], 'white');
// document.write('installMouseHandlers ' + i + '<br>');
}
}
// hover handling function
function createElemBgColorHandler(elem, color)
{
return function() {elem.style.backgroundColor = color;};
}
// get all headers from concerned table and connect click handling function
function installSortHandlers(tblId, types)
{
var table = document.getElementById(tblId);
var headers = table.getElementsByTagName('th');
for(i=0; i<headers.length; i++)
headers[i].onclick = createSorterHandler(table, i, types[i]);
}
// creates a call to sortTable() depending on the overgiven type
function createSorterHandler(table, colIndex, type)
{
return function()
{
if (type == 'number')
sortTable(table, function(row) {return extractNr(row, colIndex);}, compareNr);
else if (type == 'string')
sortTable(table, function(row) {return extractStr(row, colIndex);}, compareStr);
};
}
// helpers
function compareNr(a, b)
{
return (a.value - b.value);
}
function compareStr(a, b)
{
if (a.value > b.value)
return 1;
else if (a.value < b.value)
return -1;
else
return 0;
}
function extractNr(row, col)
{
var cells = row.getElementsByTagName('td');
return parseInt(cells[col].firstChild.nodeValue);
}
function extractStr(row, col)
{
var cells = row.getElementsByTagName('td');
return cells[col].firstChild.nodeValue;
}
function sortTable(table, extractFct, sortFct)
{
var clones = new Array();
var tbody = table.getElementsByTagName('tbody')[0];
var rows = tbody.getElementsByTagName('tr');
for(i=0; i<rows.length; i++)
{
var tmpRow = rows[i];
var val = extractFct(tmpRow);
clones[i] = {value: val, element: tmpRow};
}
clones.sort(sortFct);
for(i=0; i<rows.length; i++)
tbody.appendChild(clones[i].element);
}
// place Your HTML code here
// call the previous defined functions after the document has been loaded
installHoverHandlers();
// types must be known per column :-(
var types = ['number', 'string', 'string', 'number', 'string', 'number'];
installSortHandlers('myTable', types);