Format alternate rows by rototypeJS

There are many ways to format alternate row of a table.Here is a simple table and we want to format its rows.

Chapter 1 Basic HTML
Chapter 2 Basic CSS
Chapter 3 Basic Javascript
Chapter 1 Basic Php

Now to format the rows, we can write style for each row or we can define class for alternating rows.

Chapter 1 Basic HTML
Chapter 2 Basic CSS
Chapter 3 Basic Javascript
Chapter 1 Basic Php

So what is the secret? Here is the style that has been used for the above table

        <table> 
        <tr style="background-color:#00ced1"> 
        <td >Chapter 1</td>
        <td>Basic HTML</td> 
        </tr> 
        <tr style="background-color:#ffebcd">
        <td>Chapter 2</td> 
        <td>Basic CSS</td> 
        </tr> 
        <tr style="background-color:#00ced1"> 
        <td >Chapter 3</td> 
        <td>Basic Javascript</td> 
        </tr> 
        <tr style="background-color:#ffebcd"> 
        <td>Chapter 1</td> 
        <td>Basic Php</td> 
        </tr> 
        </table> 
        

If the number of rows are few then it is easy to follow this process. However, if the number of rows are high, then it is time confusing and boring to type the class name or style for each row. To overcome this, Javascript can be helpful and using Jquery, we can do it very easily.

Chapter 1 Basic HTML
Chapter 2 Basic CSS
Chapter 3 Basic Javascript
Chapter 1 Basic Php

Here is the jQuery Code that is used for the above table

<script type="text/javascript">
Event.observe(window,"load", function(){
$$('table#tgt tbody >tr:nth-child(odd)').each(function(itm){
itm.setStyle({backgroundColor: '#00ced1'});
});
$$('table#tgt tbody >tr:nth-child(even)').each(function(itm){
itm.setStyle({backgroundColor: '#ffebcd'});
});
});
</script>

If you are prototype user, you can get the code for protoype from here,

Format alternate row in a Table using jQuery

No  Responses to "Format alternate rows by rototypeJS"

Leave a Reply