Drew Walk
Drew Walk

Reputation: 57

Change Style CSS using Get Time Javascript

I want to change css by get user time. if the Time now is 06:00-12:00 get the Morning style. time 12:00-18:00 get the Afternoon Style. Time 18:00-06:00 get the Night Style. else get the Normal Style... how to do that.

function morning() {
    document.getElementsByTagName('BODY')[0].style.backgroundColor = "#fcfcfc";
    document.getElementsByTagName('BODY')[0].style.color = "#505050";
}

function afternoon() {
    document.getElementsByTagName('BODY')[0].style.backgroundColor = "gainsboro";
    document.getElementsByTagName('BODY')[0].style.color = "black";
}

function night() {
    document.getElementsByTagName('BODY')[0].style.backgroundColor = "#1b1b1b";
    document.getElementsByTagName('BODY')[0].style.color = "#fff";
}

function normal() {
    document.getElementsByTagName('BODY')[0].style.backgroundColor = "#fff";
    document.getElementsByTagName('BODY')[0].style.color = "#1b1b1b";
}

Upvotes: 1

Views: 522

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use setInterval() to check the time every X second (example below check every second):

setInterval(changeStyle, 1000); //1000 ms = 1 second

Then create changeStyle() function that will check the time :

function changeStyle() {
    var date = new Date();
    var current_time = d.getHours(); //Get Hour between 0 and 23

    if( current_time >= 6 && current_time <= 12 )
        morning();
    else if( current_time >= 12 && current_time <= 18 )
        afternoon();
    else if( current_time >= 12 && current_time <= 18 )
        night();
    else
        normal();
}

Or using switch() statement :

switch(true) {
    case (current_time >= 6 && current_time <= 12):
        morning();
    break;
    case ( current_time >= 12 && current_time <= 18 ):
        afternoon();
    break;
    case if( current_time >= 12 && current_time <= 18 ):
        night();
    break;
    default:
        normal();
}

Hope this helps.

Upvotes: 1

Related Questions