bingobear bingobear - 3 months ago 13
Javascript Question

jQuery highlight row within specific time

I am trying to highlight a row, when it's within a specific time range.
So actually let's say its 10:00:00 and i need to mark the row, if the time is between the start end the enddate-row.

the table:

<table class="table table-striped" id="timeTable">
<thead>
<th>Title</th>
<th>Start</th>
<th>End</th>
<th>Channel</th>
</thead>
<tbody>
<tr>
<td>Title 1</td>
<td class="dateRowStart">2016-08-10 09:00:00+02</td>
<td class="dateRowEnd">2016-08-10 11:00:00+02</td>
<td>Channel 1</td>
</tr>
<tr>
<td>Title 2</td>
<td class="dateRowStart">2016-08-10 09:30:00+02</td>
<td class="dateRowEnd">2016-08-10 12:00:00+02</td>
<td>Channel 3</td>
</tr>
<tr>
<td>Title 4</td>
<td class="dateRowStart">2016-08-10 13:00:00+02</td>
<td class="dateRowEnd">2016-08-10 15:00:00+02</td>
<td>Channel 4</td>
</tr>
</tbody>
</table>


The dateformat is the output of my postgresql db. It would be great if I could show them in our local time format (10.08.2016 - 14:15:12) but thats not my main issue here.

my (only half complete) js code to highlight:

<script>
$('#timeTable .dateRowStart').each(function () {
var dtTd = new Date($(this).html());
var dtNew = new Date();
if (dtNew.getTime() < dtTd.getTime()) {
$(this).parent('tr').addClass('highlight');
}
});

</script>


I don't know how to include
dateRowEnd
to check, if the date is still between the start/end-time. If I'm using two identical time/dates with dateformat eg. "08/10/2016 10:05:00", I'm only getting one row marked., that's the other annoying thing.

Thank you!

Answer

You could add a class to the <tr> tags themselves and then do:

HTML:

<tbody>
  <tr class="dateRow">
    <td>Title 1</td>
    <td class="dateRowStart">2016-08-10 09:00:00+02</td>
    <td class="dateRowEnd">2016-08-10 11:00:00+02</td>
    <td>Channel 1</td>
  </tr>
  ...
</tbody>

jQuery:

$('#timeTable').find('.dateRow').each(function () {
  var dtStart = new Date($(this).find(".dateRowStart").text());
  var dtEnd = new Date($(this).find(".dateRowEnd").text());
  var dtNew = new Date();
  if (dtNew >= dtStart && dtNew <= dtEnd) {
    $(this).addClass('highlight');
  } 
});

Note you only have to use .getTime() if you're doing ==, !=, ===, and !== on Date objects as seen here.

Edit: As @MarkSchultheiss suggested, separating $('#timeTable .dateRow') into $('#timeTable').find('.dateRow') has a slight efficiency boost.

Comments