Reputation: 3777
I have a a href button that I need to hide depending on the time of day or changed the background color like this:
<a class="button not-active " href="updateScheduleRequest.php?slotid=4&timeremain=120&current_date=2015-08-28&empnum=107">Assign Slot 4</a>
My CSS is configured as:
.button {
}
/* daytime */
.day
{
background-color:#e0d0b7 !important;
}
/* Sunset */
.sunset
{
background-color:#887f70 !important;
}
/* Nightime */
.night
{
display:hidden !important;
}
And then my jQuery is broken out to handle the time of day like this but it is not making any changes to the button at all? What am I missing?
// Change background depending on user's time
function applyclass()
{
var d = new Date();
var n = d.getHours();
if (n > 19)
// If time is 7PM or later apply night theme to 'body'
$('button').addClass('night');
else if (n > 16 && n < 19)
// If time is between 4PM – 7PM sunset theme to 'body'
$('button').addClass('sunset');
else
// Else use 'day' theme
$('button').addClass('day');
}
window.onload = applyclass;
Upvotes: 1
Views: 690
Reputation: 58
You may consider using a switch statement instead of if/else if/else. It tidies up the code a bit:
function applyclass() {
var d = new Date();
var n = d.getHours();
switch(true) {
case (n > 19) :
buttonClass = 'night';
break;
case (n > 16 && n < 19) :
buttonClass = 'sunset';
break;
default:
buttonClass = 'day';
}
$('.button').addClass(buttonClass);
}
Also, consider styling the .button element with default styles (like those in the 'day' class) and then only apply an additional class when necessary to override those styles. It's simpler than relying on a modifier class for each and every case.
Hope this helps!
Upvotes: 3