meow
meow

Reputation: 28164

Coding alternative shaded rows?

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

Upvotes: 2

Views: 163

Answers (3)

Michael
Michael

Reputation: 8599

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.

Upvotes: 6

Toby Hede
Toby Hede

Reputation: 37133

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

Upvotes: 2

user97410
user97410

Reputation: 724

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'});
});

Upvotes: 2

Related Questions