I maked manual dark mode button but this dont find how to do.
How can make switch to dark mode after 9pm and then switch to light mode after 7am i use html, css and javascript? Thank you.
CodePudding user response:
Somewhere in your code
const userTime = new Date().getHours()
if (userTime >= 7 && userTime < 21) {
// use light theme
} else {
// use dark theme
}
CodePudding user response:
You can get the current time of the user by using Date()
var user_hour = new Date().getHours();
if(user_hour >21 || user_hour < 7){
// activate dark mode
}
You can put it in a function and call it on window.onload
And if your users are staying long enough on your page and you want real-time mode change, you can check it repeatedly, for example in 1 minute intervals, to change the state of dark mode.
function check_dark_mode(){
var user_hour = new Date().getHours();
if(user_hour > 21 || user_hour < 7)
// activate dark mode
else
// deactivate dark mode
}
var dark_mode_interval = setInterval(check_dark_mode,60000);