So, you need to show tabular data on a webpage and make it as digestible as possible? For demo purposes, we are going to look at the top 10 most populous municipalities in Wisconsin.
See the Pen
Table Zebra Striping – Example 1 by Joe Steinbring (@steinbring)
on CodePen.
In the above example, we just have a simple HTML table using tr:nth-child(even) {background-color: #AAC4FF;} to zebra stripe the rows. It is readable but what if you want to add more municipalities or you want to update the numbers for the 2020 census? We could put the data into a JavaScript array and use Vue to display it.
See the Pen
Table Zebra Striping – Example 2 by Joe Steinbring (@steinbring)
on CodePen.
You will notice that in addition to using Vue.js to display the data, I also changed the zebra striping to tbody tr:nth-child(odd) { background-color: #AAC4FF; }, so that odd columns are highlighted instead of even columns. I added tbody before the CSS rule so that the header isn’t included, too. So, let’s add sorting now that the data is in an array of structs.
See the Pen
Table Sorting by Joe Steinbring (@steinbring)
on CodePen.
In the second demo, we bound the rows directly to the array. In this new demo, we are binding to a computed value. When you click on a column heading, it changes the value of the order and orderBy variables. The sortedArray computed value then uses the array and order variables to figure out how to display the values to the page. The next logical step is to add a search box for filtering the data.
See the Pen
Table Filtering by Joe Steinbring (@steinbring)
on CodePen.
For the above demo, we are adding query and queryBy variables in addition to a queriedResults computed value.
Now, let’s look at a quick, less that useful option for zebra striping the data.
See the Pen
Table Zebra Striping – Example 3 by Joe Steinbring (@steinbring)
on CodePen.
Let me be clear that I do not recommend doing this. The earlier examples are much better but this is something that can be done. Since the data is available in JavaScript and we are using Vue.js for the app, we can use v-bind:class to zebra stripe the table. All you need to do is modify the loop to expose the index of the array and do a modulo operation on the index value. It is more complicated and a bit unnecessary but kind of neat.
Have a suggestion for where to go from here?
[ Cover photo by Mika Baumeister on Unsplash ]