|
Learn Java Script Today | | | Over 5000 Free Fonts | | | Tutorials | | | Javascript Forum | | | Other Javascript Resources | | | Cheat Sheet |
Table Sorting is a curtesy of WebFX
Catching the eventThis part is still not finished in the W3C DOM and it is just at an early stage
of DOM level 2 so here I'll have to do some browser detection. I've added an onclick
attribute to the table and this passes an argument called event. In the IE case this is
an object that is a property of the window object but since the window object is always
in scope (like a global <table onclick="sortColumn(event)"> <thead> <tr>...</tr> ... </thead> <tbody> <tr>...</tr> ... </tbody> </table> The function sortColumn takes the target element of the event object and traverses up the tree
to see if the heading was clicked. The next step is to see if the custom attribute
Next you traverse the tree upwards until you find the actual TABLE tag. These traversing upwards is one of my most used functions and it looks like this. (In this case I've made it less general) function getParent(el, pTagName) { if (el == null) return null; //passed the root node else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // The nodeType == 1 is a test if the node is an actual element // Gecko has a bug that gives HTML tagNames in lowercase return el; else return getParent(el.parentNode, pTagName); // traverse up } Now you have all that you need to call the Getting the contentsThe first argument of the function sortTable(tableNode, nCol, bDesc) { var tBody = tableNode.tBodies[0]; var trs = tBody.childNodes; var a = new Array(); for (var i=0; i<trs.length; i++) { a[i] = trs[i]; } a.sort(compareByColumn(nCol,bDesc)); for (var i=0; i<a.length; i++) { tBody.appendChild(a[i]); } } The arrowsThe arrows are two SPAN nodes that are created at initiation and inserted into the var arrowUp = document.createElement("SPAN"); var tn = document.createTextNode("5"); // Since I'm using the webdings font this will give a nice arrow arrowUp.appendChild(tn); arrowUp.setAttribute("class","arrow"); Using the table sorting in your own tablesNext I'll show you a demo table that uses this and I'll also tell you what you need to use this in your pages. Defining the sort
|
|