Assigning Background Colors Dynamically to Zebra Tables with CSS and JavaScript
(Page 1 of 4 )
Welcome to the second installment of the series “Building Zebra Tables with CSS and JavaScript.” Comprised of four approachable tutorials, this series shows you different methodologies to help you create the so-called zebra tables with CSS. In addition, it teaches you how to use JavaScript to dynamically generate the alternate background colors of their respective even and odd rows.
As its name suggests, a zebra table is simply a regular (X)HTML table that uses one background color for its even rows and a different color for its odd ones. This makes it extremely useful for providing tabular data with a true professional appearance. However, despite the fact that these tables have become very popular with many modern web designers, admittedly, they’re pretty hard to code from scratch, especially if they’re not generated by a server-side scripting language.
Nonetheless, it’s possible, via the assistance of JavaScript, to dynamically assign alternated background colors to the table’s even and odd rows once the table in question has been created with standard markup. This powerful technique is the main focus of this series of articles. Thus, if you want to learn how to put it to work for you in a short time, then jump ahead and start reading right now!
Having already introduced the main subject of this article series, I think this is an appropriate moment to rehash the group of topics that were covered in the last article of the series, with reference to building basic zebra tables using a simple combination of CSS styles and structural markup.
Speaking specifically about this process, I’m sure that with all of the code samples that you learned in the mentioned tutorial, you’re armed with the required background to start incorporating a few zebra tables into your own web sites, especially if you want to provide your tabular data with a polished and professional look and feel.
As you saw in the previous article, a zebra table can be easily constructed by defining two (or eventually only one) CSS classes, which are assigned alternately to the odd and even rows of the table in question. However, the major drawback to building it in this manner is that each of the CSS classes has to be included manually into the markup via a “class” attribute.
Actually, this process can be quite annoying and time-consuming, particularly if the table being created contains many rows. Thus, in the course of this second installment of the series, I’m going to show you how to use JavaScript to assign background colors of the pertinent even and odd rows of the table, thus, completely automating this process.
So, are you ready to delve deeper and learn how to build zebra tables with JavaScript? Let’s get started!
Next: Review: building a basic zebra table using a CSS-based approach >>
More JavaScript Articles
More By Alejandro Gervasio