-1

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.

Milan_567
  • 11
  • 3
  • on page load, check the time. if it's after 9pm and before 7am, switch to dark mode using the same method you use on the button you maked. If it's not between 9pm and 7am, switch to not dark mode – Jaromanda X Sep 04 '22 at 08:39

2 Answers2

2

Somewhere in your code

const userTime = new Date().getHours()

if (userTime >= 7 && userTime < 21) {
  // use light theme
} else {
  // use dark theme
}
Dmitriy Zhiganov
  • 1,060
  • 1
  • 5
  • 14
2

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);