Epidemiology & Technology

Checking Dark Mode User and System Preferences in Real-time

When enabling dark mode on a website usiing say TailwindCSS using a CSS “dark” , there are two preferences in play

  • System Setting of “Prefers Dark Color Scheme”
  • User preference of a dark mode scheme for the site

The user preference will trump the system preference. Also, if tehre is no user preference, the system preference maychange due to chaneg in system time (eg. Dark mode automatcially enabled at night)

Following is a sampel code using Taiklwind CSS to address these

<!DOCTYPE html>
<html lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0" />
    <title>Demo Atlas</title>
     <link href="https://fonts.googleapis.com/css?family=Lato:300,400,900&display=swap" rel="stylesheet">
     <link href="public/css/theme.css" type="text/css" rel="stylesheet" media="screen,projection" />

</head>

<script>
    // Check on Page load ; prefer User setting
    if (localStorage.theme === 'dark') {
            document.querySelector('html').classList.add('dark')
            console.log("Dark Theme local storage  detected on page load ")
        }
        else if  (localStorage.theme == 'light') { 
            document.querySelector('html').classList.remove('dark')
            console.log("user: Light; Eval = LIGHT")
        }
        else if ( window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.querySelector('html').classList.add('dark')
            console.log("System Setting Prefers dark scheme ")
        }  else  {
            document.querySelector('html').classList.remove('dark')
            console.log("NO System Setting for Dark scheme, No user selectionof dark theme, Reverting to normal ")
        }

    // Watch Change; prefer User setting
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
        if (event.matches) { // DARK Mode System  preference
            if  (localStorage.theme == 'dark') {
                document.querySelector('html').classList.add('dark');
                console.log("System: dark, user: Dark; Eval = Dark")
            }
            else if  (localStorage.theme == 'light') { 
                document.querySelector('html').classList.remove('dark')
                console.log("System: dark, user: Light; Eval = LIGHT")
            }
            else { 
                document.querySelector('html').classList.add('dark')
                console.log("System: dark, user: None; Eval = DARK ")
            }
        }
        else {  // Light Mode System  preference
            if  (localStorage.theme == 'dark') {
                document.querySelector('html').classList.add('dark');
                console.log("System: Light, user: Dark; Eval = Dark")
            }
            else if  (localStorage.theme == 'light') { 
                document.querySelector('html').classList.remove('dark')
                console.log("System: Light, user: Light; Eval = LIGHT")
            }
            else { 
                document.querySelector('html').classList.remove('dark')
                console.log("System: Light, user: None; Eval = Light ")
            }
        }
    })   

</script>


<body>
 <header class = "block md:block">
  <div class = "flex flex-row justify-end divide-x divide-gray bg-blue dark:bg-black m-0 ">
      <button class="bg-dblue text-white py-0 px-4 hover:bg-opacity-50 text-xs "><a href="#section1" >Skip to Text</a></button>
      
      <button class=" text-white py-0 px-4  text-xs text-right" id ="resetTheme" >Reset Theme</button>
      <button class = "p-0  w-8 bg-white text-black hover:bg-opacity-50 " id ="lightTheme" >A</button>
      <button class = "p-0  w-8 bg-black text-white hover:bg-opacity-50 " id ="darkTheme">A</button>
</div>
</header>


<main class="container mx-auto bg-white text-black  dark:bg-black  dark:text-white">
  Lorem ipsum dolor sit amet consectetur adipisicing elit. Cum officia iste id dolor accusantium quibusdam ipsa iusto blanditiis odit voluptatem qui natus, impedit assumenda aspernatur repellendus perferendis unde cupiditate. Corrupti!
      </main>

<footer>
This is footer
</footer>


<script>
  // User Toggles adn Event Listeners for Dark mode
document.getElementById('resetTheme').addEventListener('click', function() {
  localStorage.removeItem('theme');
  
  if ( window.matchMedia('(prefers-color-scheme: dark)').matches) {
            document.querySelector('html').classList.add('dark')
            console.log("Removed user preference, System Setting Prefers dark scheme")
        }  else  {
            document.querySelector('html').classList.remove('dark')
            console.log("Removed user preference, System Setting Prefers Light scheme")
        }
});

document.getElementById('lightTheme').addEventListener('click', function() {
            document.querySelector('html').classList.remove('dark')
            localStorage.theme = 'light';
         console.log("User toggle Light mode")
});

document.getElementById('darkTheme').addEventListener('click', function() {
            document.querySelector('html').classList.add('dark')
            localStorage.theme = 'light';
    console.log("User toggle Dark mode")
});




</script>
</body>
</html>




Code language: HTML, XML (xml)

Related Posts