Encoding alternate shaded strings?

I want alternate rows to be highlighted in my table. what is the best way to do it, javascript, rails?

Today I am doing a simple <% num% 2%>, but this is such a general operation that I think there must be a smarter way to do it

+2


a source to share


3 answers


If you want to do this on the server side, the way for rails is to use the "loop" method, which will handle the module 2 stuff, but will also handle the namespace if you need to do nested shading variables.

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

      

eg.



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

      

The name is used to avoid collisions, if you have 2 loops happening at the same time, this is optional.

+6


a source


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

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

      



What is it, really. If you don't want to create a separate class, you can always add styling on the fly:

jQuery(document).ready(function() {
jQuery('#table tr:even').css({'backgroundColor: blue', 'font: red'});
});

      

+2


a source


This is really built into Rails - check the "loop" in the ActionView helpers.

+2


a source







All Articles