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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

  • By
    Highlighter: A MooTools Search &#038; Highlight Plugin

    Searching within the page is a major browser functionality, but what if we could code a search box in JavaScript that would do the same thing? I set out to do that using MooTools and ended up with a pretty decent solution. The MooTools JavaScript Class The...

  • By
    Implementing Basic and Fancy Show/Hide in MooTools 1.2

    One of the great parts of MooTools is that the library itself allows for maximum flexibility within its provided classes. You can see evidence of this in the "Class" class' implement method. Using the implement method, you can add your own methods to...

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!