var checkTime = function(){
for(var i = 9; i <= 17; i ){
if($.now() < i){
$("#hour-").addClass(".past");
}
if($.now() === i){
$("#hour-").addClass(".present");
}
if ($.now() > i) {
$("hour-").addClass(".future");
}
}
}
I'm trying to set a color "class 'past' 'present' 'future' depending on the hour in which the user logged into the website, between 9am to 5pm. I have set ids for every hour starting by hour-9 hour-10.. and so on until hour-17. Not quite sure how to handle this, thank you if you tried to solve this
CodePudding user response:
First you can make your code more efficient by remvoing the loop and only use the conditions but you need to use else if
as you only need one condition to be true at a time but your code can have multiple true statements. Also, i have removed .
from class names as well you dont need to add them it is used to declare the class only.
var checkTime = function(){
var dt = new Date();
var currHour=dt.getHour();
if(currHour < 9){
$("#hour-").addClass("past");
}
else if(currHour === 9){
$("#hour-").addClass("present");
}
else if(currHour > 9) {
$("hour-").addClass("future");
}
}
CodePudding user response:
I use three background colors to represent the past, present, and future.
checkTime
will be based on the input hours (login hours), to compare with the current hours, and assign a class
//Initial login hours
{
const date = new Date($.now());
$('input[type=text]').val(date.getHours());
}
//Switch class based on login hour
const checkTime = (loginHours) => {
const date = new Date($.now());
if (loginHours < date.getHours()) {
$('div').removeClass().addClass('past');
} else if (loginHours == date.getHours()) {
$('div').removeClass().addClass('present');
} else {
$('div').removeClass().addClass('future');
}
};
//Add a listener and call the method
$('input[type=button]').on('click', () => {
const loginHours = $('input[type=text]').val();
checkTime(loginHours);
});
.past {
background-color: #FFD382;
}
.present {
background-color: #82FF82;
}
.future {
background-color: #30FFFF;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="login hours" />
<input type="button" value="SUBMIT" />
<div>TEST DIV</div>