Alternate odd even table row in jQuery

No comments
We can add alternate odd even table row in jQuery, by using CSS3 pseudo element classes and some lines of jQuery codes. That will give web designers the ability to style the rows and make it attractive as we see on other website over the internet. Although, We can also add odd even classes in table rows by using php. But  in this case, we have add conditions in our code. I think jQuery is the best way to do that.

So, here is the code:
First of all create a table as below.

<table class="tg">
  <tr>
    <td>B.Tech (CSE)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (IT)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech CSE(Cloud tech. & Inf.Security)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (ECE)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (E&E)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (ME)</td>
    <td>4 years</td>
  </tr>
</table>
and then add some some css classes to make page look good.

.tg{border-collapse:collapse;border-spacing:0; width:100%;}
td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tr-even{ background:#000; color:#fff;}
.tr-odd{ background:#fff; color:#000;}
Now add jQuery code to see the the magic.

$(document).ready(function() {
$("table tr:nth-child(odd)").addClass("tr-even");
  $("table tr:nth-child(even)").addClass("tr-odd");
  });

Here is the complete code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<style>
.tg{border-collapse:collapse;border-spacing:0; width:100%;}
td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tr-even{ background:#000; color:#fff;}
.tr-odd{ background:#fff; color:#000;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$("table tr:nth-child(odd)").addClass("tr-even");
  $("table tr:nth-child(even)").addClass("tr-odd");
  });
</script>
<table class="tg">
  <tr>
    <td>B.Tech (CSE)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (IT)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech CSE(Cloud tech. & Inf.Security)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (ECE)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (E&E)</td>
    <td>4 years</td>
  </tr>
  <tr>
    <td>B.Tech (ME)</td>
    <td>4 years</td>
  </tr>
</table>

No comments :

Post a Comment