views:

91

answers:

3

I want alternative rows in my table to be shaded. what is the best way to do this, javascript, rails?

Today, i do a simple <% num % 2%>, but this is such a common operation that i think there should be a smarter way to do it

+2  A: 

You can do that very easily using jQuery, if that's an option. Link to the jQuery library in the head, and ideally give the table an id or class so that you can identify it, and create a class that half the rows will get. Then, put this in your javascript:

jQuery(document).ready(function() {
jQuery('#table tr:even').addClass('stripes'); //could also be tr:odd
});

That's it, really. If you don't want to create a separate class, you can always add the style on the fly:

jQuery(document).ready(function() {
jQuery('#table tr:even').css({'backgroundColor: blue', 'font: red'});
});
I might be missing something, but how would you determine what rows should have the tr:even attribute?
Casey
What the selector is doing is only choosing rows that are even (0, 2, 4 etc.) so that you don't need to. You can set it to odd, if you prefer. So every other row will have your 'stripes' class attached/receieve the style declaration.
Thanks! That's good to know.
Casey
+2  A: 

This is actually built-in to Rails - check the "cycle" method in ActionView Helpers.

Toby Hede
+6  A: 

If you're willing to do it on the server side, rails intended way is for you to use the "cycle" method, this will handle the modulus 2 stuff, but will also handle namespacing if you need to do nested alternating shading.

http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M001753

e.g.

<%= cycle("even", "odd", :name => "row_class") -%>

The name is just used to avoid collisions if you've got 2 cycles going on at the same time, it's optional.

Michael
+1: if the OP does not want to use modulo, then using then prescribed method for his platform is the way to go
RedFilter
thanks! <%= cycle("even", "odd", :name => "row_class") -%>why the "-" at the end of the -%> though?
ming yeow
The trailing -%> just tells ERB to remove any whitespace after the closing %> tag. It's generally not necessary if you're just writing out a class name. I just wrote it out of habit.
Michael