How to change the color of alternate row with Css or JavaScript or Jquery?

By

Change Color with Javascript
I have a table and i want to change the color of alternate row or customize the row color.
i want output like below picture
change the color of alternate row

There are so many way to do this but i will explain here three approach
1. With the help of CSS.
2. With the help of JavaScript.
3. With the help of JQuery.

Code Sample [SQL SERVER]
To do this first i create the table structure for the same.Html of table is given below
<table id="tblid" width="100%">
    <tr><td>Change Row Color 1</td></tr>
    <tr><td>Change Row Color 2</td></tr>
    <tr><td>Change Row Color 3</td></tr>
    <tr><td>Change Row Color 4</td></tr>
    <tr><td>Change Row Color 5</td></tr>
    <tr><td>Change Row Color 6</td></tr>
</table>
This table have 6 row and table id is tblid.
1. With the help of CSS
   If we want to change the color of alternate row like even odd row then CSS is the best option.Css      code is
    #tblid tr:nth-child(even)
    {
        background: #d3d3d3;
    }
    #tblid tr:nth-child(odd)
    {
        background: #939393;
    }
to implement this you have to do nothing just copy the table structure and css code and just paste in your project.

2. With the help of JavaScript
<script type="text/javascript">
    function ChangeRowColor() {
        var tblrowsTag = document.getElementById('tblid').getElementsByTagName('tr');
        for (i = 0; i < tblrowsTag.length; i++) {
            if (i % 2 == 0) {
                tblrowsTag[i].style.backgroundColor = '#d3d3d3';
            }
            else {
                tblrowsTag[i].style.backgroundColor = '#939393';
            }
        }
    }
</script>
 Call ChangeRowColor() method onload of body .

3. With the help of JQuery
<script type="text/javascript">
        $(document).ready(function () {
            $("#tblid tr:even").css("background-color", "#d3d3d3'");
            $("#tblid tr:odd").css("background-color", "#939393");
        });
 </script>
To use the Jquery you have to register Jquery library in your project.
Explanation

I hope this is helpful to you .Here i used three way .Its tested in all new version of browser and its working fine. If you want to custom the row color like below

Custom the color of alternate row
Customize the alternate row color
Then use below code
<script type="text/javascript">
    var colors = new Array('#d3d3d3', '#a8a8a8', '#7e7e7e');
    var tblrowsTag = document.getElementById('tblid').getElementsByTagName('tr');

    for (i = 0; i < tblrowsTag.length; i++) {
        ApplyColor(tblrowsTag[i], i);
    }
    function ApplyColor(rowTag, i) {
        rowTag.style.backgroundColor = colors[i % colors.length];
    }
</script>

0 comments:

Post a Comment