1

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";
}
1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.