MooTools Zebra Tables Plugin

By  on  

Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors.

The CSS

.highlight		{ background:#d5fcdc; }
.even			{ background:#fff; }
.mo			{ background:#e3f1fb; }
.odd			{ background:#eee; }
.zebra th		{ padding:5px; background:#ddd; border-bottom:1px solid #999; text-align:left; font-weight:bold; }
.zebra td		{ padding:5px 20px 5px 5px; border-bottom:1px solid #ddd; }

The above CSS is extremely basic. I've styled the <TH> tag so that it stands out from table rows. There are four states of rows in my zebra table: highlighted (or "clicked on"), regular even and odd, and a mouseover state -- these are represented by the "even", "mo", "highlight", and "odd" classes. I've added padding and a bottom border to the <TD>'s for presentation.

The XHTML

<table class="zebra" cellpadding="0" cellspacing="0">
	<tr>
		<th>Award</th>
		<th>Actor</th>
		<th>Film</th>
	</tr>
	<tr>
		<td>Actor In A Leading Role</td>
		<td>Daniel Day-Lewis</td>
		<td>There Will Be Blood</td>
	</tr>
	<tr>
		<td>Actress In A Leading Role</td>
		<td>Marion Cotillard</td>
		<td>La Vie en Rose</td>
	</tr>
	<tr>
		<td>Actor In A Supporting Role</td>
		<td>Javier Bardem</td>
		<td>No Country For Old Men</td>
	</tr>
	<tr>
		<td>Actress In A Supporting Role</td>
		<td>Tilda Swinton</td>
		<td>Michael Clayton</td>
	</tr>
	<tr>
		<td>Directing</td>
		<td>Joel Coen and Ethan Coen</td>
		<td>No Country For Old Men</td>
	</tr>
	<tr>
		<td>Writing</td>
		<td>Diablo Cody</td>
		<td>Juno</td>
	</tr>
</table>

The above table is a simple, standard table. The only detail of note is that this table is given the "zebra" class, which signals to MooTools that this table should be zebra-ized.

The JavaScript Class

/* classes */
var ZebraTables = new Class({
	//initialization
	initialize: function(table_class) {

		//add table shading
		$$('table.' + table_class + ' tr').each(function(el,i) {

			//do regular shading
			var _class = i % 2 ? 'even' : 'odd'; el.addClass(_class);

			//do mouseover
			el.addEvent('mouseenter',function() { if(!el.hasClass('highlight')) { el.addClass('mo').removeClass(_class); } });

			//do mouseout
			el.addEvent('mouseleave',function() { if(!el.hasClass('highlight')) { el.removeClass('mo').addClass(_class); } });

			//do click
			el.addEvent('click',function() {
				//click off
				if(el.hasClass('highlight'))
				{
					el.removeClass('highlight').addClass(_class);
				}
				//click on
				else
				{
					el.removeClass(_class).removeClass('mo').addClass('highlight');
				}
			});

		});
	}
});

The class accepts one parameter, which is the class given to tables that should be Zebra-ized. Upon initialization, the class cycles through each table row. During the row looping, the row is given its odd or even CSS class, and a listener is added to the row to highlight the row upon mouseover. The above JavaScript could be placed into an external JavaScript file.

The JavaScript Implementation

/* do it! */
window.addEvent('domready', function() {
	var zTables = new ZebraTables('zebra');
});

To implement ZebraTables, all you need to do is add the above code to any given page.

Do you have any suggestions for my zebra tables? Let me know!

Recent Features

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    Optimize Your Links For Print Using CSS â Show The URL

    When moving around from page to page in your trusty browser, you get the benefit of hovering over links and viewing the link's target URL in the status bar. When it comes to page printouts, however, this obviously isn't an option. Most website printouts...

  • By
    iPhone Click Effect Using MooTools or jQuery

    One thing I love about love about Safari on the iPhone is that Safari provides a darkened background effect when you click a link. It's the most subtle of details but just enforces than an action is taking place. So why not implement that...

Discussion

  1. Slick as hell. I love it.

    Someday I actually want to do a site that has all kinds of tabular data so I can get the chance to use some of this stuff and prove that tables and be styled beautifully.

  2. George

    Hey David

    Cheers for the great util. I have amended it slightly to allow a single select (highlite) only.
    We are currently using mootools 1.11 and wouldn’t want to productionise the 1.2 beta version on our site. Can you give me any pointers as to how i could get your util working against 1.11?
    Thanks
    George

  3. Thanks George. To tell you the truth, this code should work on Moo 1.1. If not, you can always download the 1.1 compatibility scripts.

  4. chadSmith

    This is fantastic! Thanks so much for the post! I’ve known about MooTools but didn’t know this was possible. Thanks again.

  5. I’m wondering if an even better way of marking it up would be to add in a thead and tbody:

    <table class="zebra" cellpadding="0" cellspacing="0">
    <thead>
    <tr>
    <th>Award
    <th>Actor
    <th>Film
    </tr>
    </thead>
    <tbody>
    <tr>

    </tr>
    </tbody>
    </table>

    That way, you could only apply the classes to all table rows within the tbody and style the th elements of the thead without any javascript applied to it.

  6. kemal

    with moo 1.11 this code works like a charm..

  7. @Trevor: Good suggestion!

    @Kemal: Yep, I originally coded it in 1.1 and saw that it translated perfectly into 1.2.

  8. Annis

    Hey David,
    you can actually simplify your class. Since you say in your example that it’s for MooTools 1.2, you could add the CSS3 selectors (:odd, :even), so there goes a line. And you can use the toggleClass method in the onClick handler so there goes another line (and the if…). If I counted correctly, that makes it the smallest class for this I’ve ever seen. Great work!

    Annis

  9. andy

    Very nice, easy to modify too.

  10. @Annis: I want every row regardless (so that I can attach the mouseover effect), so using “:odd” and “:even” would actually create more code.

  11. anthony

    Hello david,

    I’m running into an issue I hope you can help with. I am using the following code:

     window.addEvent('domready', function(){
            $('pinstripe').addEvent('click',function(e){
            $$('table').each(function(table){
            $ES("tr", table).each(function(row,i){
            if ( i % 2 == 1 )
               row.toggleClass( "odd" );
                   });
                 });
              });
            }); 
    

    my problem is that i have tables within my tables(hidden unless opened by the user) and the function is pinstriping those tables as well, which I don’t want it to do. I know I need to identify my table that I do want pinstriped by its id and then pinstripe the direct tr children, however this is where my lack of js experience falters. Thanks for any help you can give.

  12. qwan

    I am n00b with javascript, so please tell me how is this related to mootools.
    You have given me the css, the javascript and the javascript needed to “activate it”(and the xhmtl too). So how is mootools involved?
    I am asking this because I want to implement this inside of joomla and 1.5 has mootools.
    So how is this is going to help.
    Will i need mootools.js to make this work if I was using it on a plain html site?
    Thanks

  13. Brandon

    So….can this collection of tools be used within WordPress?

  14. yLinRain

    Hey David:

    Counld it by col/colgroup?ths!

  15. Hello,
    Great post and really useful for me.

    I have a data-heavy site and I would like to style the empty cells differently. Can you help me? I have no idea how to mark these up in javascript.
    Thank you.

  16. Seems unnecessarily complex to my, why don’t you use :

    $$('table.zebra tr').each(function(el, num) {el.addClass(num % 2 ? 'odd' : 'even');});
    

    or better yet:

    $$('table.zebra tr:even').addClass('odd');
    

    and make the even class the standard style for a zebra tr td.

  17. Yossi

    Is there any sorting feature that can add to this excellent class ?
    Also, is there a way to make pagination on the same tables ?

    Thanks

  18. abdessamad

    nice tuto :) thx a lot!!! i have a Q? mootools and ui any suggestion (sorry for my english !!!!)

  19. shuaib

    Hi!

    Can we use this table in Joomla? any plugin for that?

  20. Da master

    Useless. Pointless.
    Zebra tables are perfectly doable only with pure CSS and no Javascript.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!