Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you write an alternating row function using modulus in CoffeeScript?

I've got an example here of a typical chunk of JavaScript (code that would apply a background style class to an alternating odd or even row in a table). I'm trying to rewrite this in CoffeeScript in my attempt to learn that. The CoffeeScript range syntax is different and more Ruby-esque. I'd really appreciate an example of how you would do this?

   function alternate(id){ 
     if(document.getElementsByTagName){  
       var table = document.getElementById(id);   
       var rows = table.getElementsByTagName("tr");   
       for(i = 0; i < rows.length; i++){           
     //manipulate rows 
         if(i % 2 == 0){ 
           rows[i].className = "even"; 
         }else{ 
           rows[i].className = "odd"; 
         }       
       } 
     } 
    }

Update

I'm using JQuery and trying this but it doesn't work (it makes all rows #efefef):

$(document).ready ->
    rowCount = $('tbody tr')
    for row in rowCount        
        if row.length % 2 == 0
            $('tbody tr').css('background-color', '#363636')
        else
            $('tbody tr').css('background-color', '#efefef')
like image 432
Handloomweaver Avatar asked Dec 21 '22 21:12

Handloomweaver


2 Answers

You may also be interested in the even / odd meta selectors provided by jquery

$('tbody tr:even').css 'background-color', '#363636'
$('tbody tr:odd').css 'background-color', '#efefef'
like image 31
minikomi Avatar answered Dec 24 '22 11:12

minikomi


A little more concise:

for row, i in $('tbody tr')
  color = if i % 2 is 0 then '#363636' else '#efefef'
  $(row).css 'background-color', color
like image 76
jashkenas Avatar answered Dec 24 '22 10:12

jashkenas