I’m working on a JS project where I create a daily scheduler and each hour should be color coded based on if it is past, present, or the future.
The schedule goes from 9am to 5pm. Currently it is applying the class for future to every block, so every row shows up as green. Instead, say if it were 11am, then the row for 11am would be highlighted red for present time, the rows for the hours before 11am would be grey or transparent and the hours in the future would be green.
I have set Ids for each of my hour blocks to parse through and compare with the current hour, but for some reason it isn’t working. I already have the classes set up in my CSS for past present and future.
var blocks = document.getElementsByClassName("description");
var hourBlock = parseInt(moment().format('H'));
Array.from(blocks).forEach(description => {
let idString = description.id, rowHour;
if (idString) {
rowHour = parseInt(idString);
}
if (rowHour) {
if (hourBlock === rowHour) {
$(".description").addClass("present")
} else if (hourBlock < rowHour) {
$(".description").addClass("past")
} else {
$(".description").addClass("future");
}
}
});
>Solution :
The issue is because in your loop you’re updating the classes of all .description elements, not the one in the forEach loop.
To fix the problem, and make your code much more succinct, you can pass a function to jQuery’s addClass() method which will be evaluated against every element in the collection individually. In this function you can check the id of the element against the current hour (which you don’t need MomentJS for) and set the appropriate class. Try this:
// let nowHour = (new Date()).getHours();
let nowHour = 13; // hard-coding value for this demo
$('.description').addClass(function() {
return +this.id === nowHour ? 'present' : +this.id < nowHour ? 'past' : 'future';
});
.present { background-color: #C00; }
.past { background-color: #CCC; }
.future { background-color: #0C0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="description" id="9">9am</div>
<div class="description" id="10">10am</div>
<div class="description" id="11">11am</div>
<div class="description" id="12">12pm</div>
<div class="description" id="13">1pm</div>
<div class="description" id="14">2pm</div>
<div class="description" id="15">3pm</div>
<div class="description" id="16">4pm</div>
<div class="description" id="17">5pm</div>