|
Helping ordinary people create extraordinary websites! |
Striped Tables Using JavaScriptBy Paul McCarthy2008-01-23
The JavaScript So you can see what we're aiming to do, check out this fully functioning example. Open the 'js.js' file you've downloaded and let's get started! Registering an eventThe first task is to create an event that occurs when the page has loaded. Rather than trying to execute a function call using within the HTML page we're going to use Simon Willison's addLoadEvent(func). This will allow us to add function calls once the page has loaded. Type the following JavaScript into the .js file: function addLoadEvent(func) Collecting table elementsCreate an empty function in your JavaScript file called fgetAllDataTables. To avoid any JavaScript errors with the script, check to see if the command getElementsByTagName is available: function fgetAllDataTables() The second task is to create collections of the table elements that will be manipulated by the JavaScript. Use the getElementsByTagName command to retrieve all the tables. Next assign all tables to the variable eleTables, as follows: function fgetAllDataTables() Looping through tablesAll tables have been assigned to the variable eleTables as an HTML object collection. The next step is to loop through all the tables and check to see if a class of datatable, class="datatable", has been assigned to any of them. function fgetAllDataTables() The fgetAllDataTables() function is almost complete. Our next task is to apply the stripes to the tables with a class of datatable, class="datatable". We'll do this by passing any tables with this class to a new function called fStripes, as follows: function fgetAllDataTables() Striped rowsWe've passed the fStripes function any tables that need to be made stripey. Create an empty function called fStripes: function fStripes(eleTable) Every other row requires a class of trgrey applied to it. The class has been predefined in an external stylesheet: .trbg First create a loop based on the number of rows contained by the table. Then apply the class to every other row starting from 1, as follows: function fStripes(eleTable) Tutorial Pages: » Introduction » The JavaScript » Benefits of JavaScript striped tables |
|