Home > OS >  How can I change the lite mode to dark mode according to the user's time?
How can I change the lite mode to dark mode according to the user's time?

Time:12-31

How can I change the lite mode to dark mode according to the user's time using JS ? `

// function to set a given theme/color-scheme
  function setTheme(themeName) {
     localStorage.setItem('theme', themeName);
     document.documentElement.className = themeName;
}
// function to toggle between light and dark theme
function toggleTheme() {
  if (localStorage.getItem('theme') === 'theme-dark') {
     setTheme('theme-light');
  } else {
     setTheme('theme-dark');
  }
}
// Immediately invoked function to set the theme on initial load
(function () {
  if (localStorage.getItem('theme') === 'theme-dark') {
     setTheme('theme-dark');
     document.getElementById('dark-light-mode').checked = false;
 } else {
     setTheme('theme-light');
     document.getElementById('dark-light-mode').checked = true;
 }
})();

`

`

   <label id="switch" >
     <input type="checkbox" onchange="toggleTheme()" id="dark-light-mode">
     <span ></span>
   </label>

`

I wanna change theme between light and dark via user's time

CodePudding user response:

Use can Date object and apply theme according to the selected time

You can do something like this.


 let hour = (new Date).getHours();

  if (hour >= 18) {
     setTheme('theme-dark');
  } else {
     setTheme('theme-light');
  }

It will apply dark theme if the time is greater then 18

You would also need setInterval so it will watch the time and fire event based on the condition.

  • Related