user11433880
user11433880

Reputation:

Highlight current date

My function displays the current date along with the next 60 days however I want the current date to be highlighted. What would be the best approach?

var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();

var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; 

document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;


for(var day = 0; day < 60; day++) {
    var date = new Date();
    date.setDate(date.getDate() + day);

    var cell = document.createElement("li");
    var cellText = document.createTextNode(day);

    var date = ('0' + date.getDate()).slice(-2) + ' '
    + monthNames[date.getMonth()] + ' '
    // + date.getFullYear();

    cell.innerHTML = date;
    dateRange.appendChild(cell);
}

Upvotes: 1

Views: 942

Answers (2)

RobG
RobG

Reputation: 147413

Another way to go about it is to create a timestamp in the same format as the dates in the range then search for it.

E.g. the following, which puts formatting into a separate function and removes code that wasn't being used:

function formatDate(d){
  let monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; 
  return ('0 ' + d.getDate()).slice(-2) + ' '
                + monthNames[d.getMonth()];
}

function highlightToday() {
  let today = formatDate(new Date());
  let cells = document.querySelectorAll('#calendar-table-range > li');

  for (var i=0, iLen=cells.length; i<iLen; i++) {

    if (cells[i].textContent == today) {
      cells[i].style.color = 'red';
      return;
    }
  }
}

var date = new Date();
var dayInt = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();

var dateRange = document.getElementById('calendar-table-range');
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; 

document.getElementById("month").innerHTML = monthNames[month];
document.getElementById("year").innerHTML = year;


for(var day = 0; day < 6; day++) {
    var date = new Date();
    date.setDate(date.getDate() + day);

    var cell = document.createElement("li");
    var date = formatDate(date);
    cell.innerHTML = date;
    dateRange.appendChild(cell);
}
<div id="month"></div>
<div id="year"></div>
<input type="button" onclick="highlightToday()" value="highlight today">
<ol id="calendar-table-range">
</ol>

Upvotes: 0

coreyward
coreyward

Reputation: 80051

Since you're always showing the next 60 days, the current date is always the first date in the list, so it's easy to target with a CSS selector. For example:

#calendar-table-range li:first-child {
  background-color: yellow;
}

Upvotes: 4

Related Questions