Search code examples
javascripthtmllinuxapache2darkmode

HTML Dark Mode With Pure JavaScript


I'd like to add dark mode to my website with javascript. It works technically, but not the way I wanted it to. It only set the body color to black. But the challange is to set color to the "< div >" tags. Honestly I don't really know JavaScript, so I don't know how to do it. Here is my code:

document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
function darker() {
     if ( sessionStorage.getItem('bg') === 'rgb(241, 241, 241)') {

            sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
            sessionStorage.setItem('cc', '#fff');
            sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
            sessionStorage.setItem('cardcc', '#fff');


     }
    else if (sessionStorage.getItem('bg') == null || undefined) {
        sessionStorage.setItem('bg', 'rgb(6, 23, 37)');
        sessionStorage.setItem('cc', '#000');
        sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
        sessionStorage.setItem('cardcc', '#fff');

    }
    else if( sessionStorage.getItem('bg') === 'rgb(6, 23, 37)') {

        sessionStorage.setItem('bg', 'rgb(241, 241, 241)');
        sessionStorage.setItem('cc', '#000');
        sessionStorage.setItem('cardbg', 'rgb(5, 15, 36)');
        sessionStorage.setItem('cardcc', '#fff');


    }
document.body.style.backgroundColor = sessionStorage.getItem('bg');
document.body.style.color = sessionStorage.getItem('cc');
document.div.style.backgroundColor = sessionStorage.getItem('cardbg');
document.div.style.color = sessionStorage.getItem('cardcc');
}
<html>
<head>
<style>
body {
  background-color: #f1f1f1;
  color: #000;
}

.card {
  background-color: red;
  color: black;
}
</style>
</head>
<body>
<div class="card">
<h5>Title</h5>
<p>Some text...</p>
<p>Another text..</p>
</div>
</body>
<script src="assets/js/darker.js"></script>
</html>


Solution

  • You could store your themes in an object and switch them during runtime using document.documentElement.style.setProperty()

    Example:

    const dark = {
      'background-color': '#FFFFFF'
    }
    
    const light = {
      'background-color': '#000000'
    }
    

    In your CSS (Note: to only style div's use body > div)

    --background-color: #000000 // this is the default
    
    body > div {
     background-color: var(--background-color);
    }
    

    And finally if you need to switch the theme you can do:

    function setTheme(a_oTheme) {
      Object.keys(a_oTheme).forEach(k =>
        document.documentElement.style.setProperty(`--${k}`, a_oTheme[k])
      );
    }