Skip to content Skip to sidebar Skip to footer

Moment / Jquery - Silly Issue With A Simple Timeline

I had alot of help from this community getting my timeline report to work correctly. The way this is setup is that it will get a date range by checking the ajax return. Then it wil

Solution 1:

For the missing last day, you're setting lastDate to the beginning of May 4th -- it needs to be at the end of that day instead:

var lastDate = moment("2016-05-04").endOf('day');

The repeated events are because the code I wrote for your last question assumed that the last date in the list of entries would be the last date you'd want to display, so it didn't need to handle the case where you continue to loop through dates after running out of entries. That can be fixed by, well, handling that case:

if (i === data.length) {
   // we've run out of entries; don't try to check past the end of the data array:
   ret += "<tr><td>No entries today.</td></tr>";   
} else if (moment(data[i].Date) > thisDate.endOf('day')) {
  // The next entry is later than this day.
  ret += "<tr><td>No entries today.</td></tr>";
} else {
  // starting at entry i, display all entries before the end of thisDate:
  for (var j = i; j < data.length; j++) {
    if (moment(data[j].Date) < thisDate.endOf('day')) {
      // the next one belongs on thisDate, so display it:
      ret += '<tr><td>' + moment(data[j].Date).format("HH:mm") + " - " + data[j].Description + "</td></tr>";
    } else {
      // next one is not for thisDate, so we can go on to the next day.
      i = j; // It'll start here, so we don't waste time looping over past events
      break; // (out of the inner loop)
    }
  }
  // Did we run out of entries?  If so, need to update i here to prevent repeated display
  if (j === data.length) {
    i = j;
  }
}

https://jsfiddle.net/tt35rnoo/

However...

Given the number of times you've asked variations on this question, it may be better to keep things simple here. Try this less efficient but much less complicated version, which doesn't try to skip past already-displayed events on each loop:

  // loop through each day in that range
  var ret = ""; 
  for (var thisDate = firstDate; thisDate <= lastDate; thisDate.add(1, 'days')) {
    ret += '<tr><th>' + thisDate.format("dddd, MMMM D") + "</th></tr>";
    var showedAnEventToday=false;

    for (var j = 0; j < data.length; j++) {
        if (
            moment(data[j].Date) > thisDate.startOf('day') && 
            moment(data[j].Date) < thisDate.endOf('day')
        ) {

          showedAnEventToday = true;
          ret += '<tr><td>' + moment(data[j].Date).format("HH:mm") + " - " + data[j].Description + "</td></tr>";
        } 
    }
    if (!showedAnEventToday) {
        ret += '<tr><td>No events today.</td></tr>';
    }
  }
  $('#x').html(ret);

https://jsfiddle.net/ejaca00t/


Post a Comment for "Moment / Jquery - Silly Issue With A Simple Timeline"