0

I have a table which is filled from several jsp pages. I wanna alternate the table <tr> background after the page is loaded.

I have to call this script:

function alternate(id){ 
    var table = document.getElementById(id);   
    var rows = table.getElementsByTagName("tr");   
    for(i = 0; i < rows.length; i++){  
        if(i % 2 == 0){ 
            rows[i].style.backgroundColor = "#84939a"; 
          }else{ 
            rows[i].style.backgroundColor = "#FFFFFF";
          }      
    }
    }

How can I do that? Thanks in advance

3 Answers 3

3

if you are using JQuery you can use:

$(document).ready(function(){

.. your code

});

but doing alternating colors is much simpler with css

tr:nth-child(odd)       { background-color:#84939a; }
tr:nth-child(even)      { background-color:#FFFFFF; }
0
0

Just put your <script> just before the closing </body> tag and call it:

<script>
function alternate(id){ 
var table = document.getElementById(id);   
var rows = table.getElementsByTagName("tr");   
for(i = 0; i < rows.length; i++){  
    if(i % 2 == 0){ 
        rows[i].style.backgroundColor = "#84939a"; 
      }else{ 
        rows[i].style.backgroundColor = "#FFFFFF";
      }      
}
}
alternate();
</script>
0
0
document.onload = function() {alternate(id)};

Just make sure to replace id with the id you want wrapped in quotes.

Not the answer you're looking for? Browse other questions tagged or ask your own question.