Bad Dub Bad Dub - 5 months ago 16
HTML Question

Add alternating table row colour based on date?

I have a table in html and the first column in each row contains a date. I want to give some sort of separation based on date. So all rows with todays date would be dark grey, yesterdays row would be light grey and then two days ago would be a grey again and so on.

Is there an easy way to do this?

Thanks

Answer

To have alternating rows a different colour (with multiple rows having the same date), you'll have to use jQuery to iterate through all the table rows to check whether it should color that row or not.

Below is the jQuery, HTML and CSS for an example.

// iterate over each row
var tableDate = $("#MyTable tbody").parents('tr:first').find('td:first').text();
var shouldColor = true
$("#MyTable tbody tr").each(function(i) {
    // find the first td in the row
    var value = $(this).find("td:first").text();
    // display the value in console
				if (value == tableDate) {
        	if (shouldColor == true) {
        		$('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate");
            } 
         
        } else {
        		if (shouldColor == false) {
            	shouldColor = true
              $('#MyTable tbody tr:nth-child(' + (i + 1) + ')').addClass("alternate");
            } else {
            	shouldColor = false
            }	
        }
    		
tableDate = value
});
#MyTable {
		width:100%; 
		border-collapse:collapse; 
	}
#MyTable td { 
		padding:7px; border:blue 1px solid;
	}

#MyTable tr {
		background: light-grey;
	}
  
  

#MyTable .alternate { 
		background: red;
	}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="MyTable" >
    <tbody>
  <tr>
    <td>4/4/2016</td>     <td>Running</td>
  </tr>
  <tr>
    <td>4/4/2016</td>     <td>Swimming</td>
  </tr>
    <tr>
    <td>5/4/2016</td>     <td>Running</td>
  </tr>
  <tr>
    <td>6/4/2016</td>     <td>Swimming</td>
  </tr>
    <tr>
    <td>6/4/2016</td>     <td>Swimming</td>
  </tr>
    <tr>
    <td>6/4/2016</td>     <td>Swimming</td>
  </tr>
    <tr>
    <td>6/4/2016</td>     <td>Swimming</td>
  </tr>
    <tr>
    <td>7/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>7/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>8/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>9/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>10/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>11/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>11/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>12/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>12/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>12/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>13/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>13/4/2016</td>     <td>Swimming</td>
  </tr>
  <tr>
    <td>13/4/2016</td>     <td>Swimming</td>
  </tr>
  
</tbody>
</table>