user3369743
user3369743

Reputation: 35

Add a class to a div after day of month has passed (javascript)

I would like to have 31 divs. One for every day of a month. But I want divs for previous days to look different from future days. I'm trying to figure out the best way to do this.

EDIT: I can see how unclear my question was. I am looking for javascript to act on divs that have been created separately. Not for the javascript to create the divs.

One thought was to have -

<div id="day-1" class="something">content</div>
<div id="day-2" class="something">content</div>
<div id="day-3" class="something">content</div>

then, some form of loop checking if the day- id is < d.getDate() and if so document.getElementById("").className = " pastdate";

then .pastdate can let me change the appearance.

I just want to check if I'm on the right track or if there's an easier way?

Upvotes: 0

Views: 118

Answers (3)

bloodyKnuckles
bloodyKnuckles

Reputation: 12089

Append a dynamic stylesheet to the document head:

const today = new Date();
const today_date = today.getDate();

const days = [...Array(today_date).keys()].splice(1).map(
  day => `#day-${day}`
).join(',');

const styles = `
#day-${today_date} {
  font-weight: bold;
  color: green;
}

${days} {
  color: silver;
}
`;

var styleSheet = document.createElement("style");
styleSheet.innerText = styles;
document.head.appendChild(styleSheet);
<div id="day-18" class="something">content</div>
<div id="day-19" class="something">content</div>
<div id="day-20" class="something">content</div>
<div id="day-21" class="something">content</div>
<div id="day-22" class="something">content</div>
<div id="day-23" class="something">content</div>
<div id="day-24" class="something">content</div>
<div id="day-25" class="something">content</div>
<div id="day-26" class="something">content</div>

Starting by instantiating a Date object, assigning it to variable today, then using it's method getDate() to assign the current day number of the month to variable today_date.

Next, instantiating an array with that number of elements using Array object and providing today_date for it's parameter, then get it's key values using it's keys() method, along with the spread operator and array literal notation to populate the array. keys() provides an array of numbers, 0 through yesterday's day number, so splice() the array starting from the second element, index 1, to the end, which results in an array containing day numbers 1 through yesterday.

The array chain is continued by map'ing it to string interpolate the day numbers (keys) into an array of strings containing "#day-" and the day number. Now join'ing this array of strings into a single, plain string, then interpolating it into the variable styles.

Finally create a stylesheet element using createElement() and append it to the head using appendChild().

Upvotes: 1

I write some code for you. I think you need this one.

const days = document.getElementById('days');

const date = new Date();
const currentYear = date.getFullYear();
const currentMonth = date.getMonth();
const currentDay = date.getDate();

const currentMonthDaysCount = (year, month) => {
    return new Date(year, month, 0).getDate();
};

for(let i = 0; i < currentMonthDaysCount(currentYear, currentMonth + 1); i++) {
    let div = document.createElement('div');
    if(i < currentDay - 1) {
        div.classList.add('pastDays');
    } else if (i == currentDay - 1) {
        div.classList.add('currentDay');
    }
    div.innerHTML = i + 1;
    days.appendChild(div);
}
#days {
    display: flex;
    justify-content: flex-start;
    gap: 10px;
    flex-wrap: wrap;
}

#days div {
    width: 50px;
    height: 50px;
    background-color: gray;
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 1.5rem;
    font-weight: bold;
}

#days div.pastDays {
    background-color: aqua;
}

#days div.currentDay {
    background-color: red;
}
<div id="days"></div>

Upvotes: 1

Neeraj Kumar
Neeraj Kumar

Reputation: 504

Not sure how exactly you are going to use this but I would give you an idea how to achieve this. You can alter my code for you purpose or uses.

function getDaysInCurrentMonth() {
  const date = new Date();
  return new Date(
    date.getFullYear(),
    date.getMonth() + 1,
    0
  ).getDate();
}

var toAdd = document.getElementById("dayContainer");
const totalDays = getDaysInCurrentMonth();
const currentDate = new Date();
const currentDay = currentDate.getDate();
let daysClass;

for(var i=1; i < totalDays+1; i++){
   var newDiv = document.createElement('div');
   newDiv.id = 'day'+i;
   i < currentDay ? daysClass="days pastDay" : ( i == currentDay ? daysClass="days currentDay" : daysClass="days futureDay");
   newDiv.className = daysClass;
   newDiv.innerHTML += i;
   toAdd.appendChild(newDiv);
}
.days{padding:5px; margin:5px; width:50px; height:20px;  text-align:center; font-weight:bold; color:#fff; display:block; position:relative; float:left; }
.pastDay{background:#FFA500; }
.futureDay{background:#0096FF; }
.currentDay{background:#008000; }
.dayContainer{width:100%; display:block; position:relative; float:left; }
<div id="dayContainer" class="dayContainer"></div>

All the best!

Upvotes: 1

Related Questions