0

I'm new to all this so sorry if it's a stupid question. Basically, I have my CSS colours set up as three :root functions and the JavaScript has everything done for a light mode/dark mode toggle but now I want it so that when dark mode is true the colours in CSS change. Is there a way of doing this? (Even if it means duplicating the CSS and making the second one have the dark mode colours with JS choosing which file to choose based on the true or false statement of the toggle in HTML?

HTML/JS:

<li>
    <label>Night mode</label>
    <br>        
    <input type="checkbox" name="Nightmode" class="switch" id="nightModeCheckBox">
    <script>
        var nmbc = document.getElementById("nightModeCheckBox").checked;
        if (localStorage.getItem("nightMode") == "true"){
            document.getElementById("nightModeCheckBox").checked = true;
        }
    </script>
</li>
<li>
    <button onclick="settingsSave()" class="save">Save</button>
    <p id="saveText"></p>
    <script>
        function settingsSave() {
        var nmbc = document.getElementById("nightModeCheckBox").checked;
        if (typeof(Storage) !== "undefined") {
        localStorage.setItem("nightMode", nmbc);
        alert(localStorage.getItem("nightMode"));
        } else {
        alert("It seems your browser doesn't support local storage. Try updating it or using a different browser.");
        }
        }
        console.log(nmbc)
    </script>
</li>

CSS:

:root{
    --color1: White;
}

:root{
    --color2: rgb(230, 230, 230);
}

:root{
    --colorText: black;
}
wazz
  • 4,953
  • 5
  • 20
  • 34
  • where are you using the color*n* values? – Bravo Oct 23 '19 at 03:28
  • Just so you know, there are media queries for dark mode. Take a look at https://css-tricks.com/dark-modes-with-css/. As for updating css styles with Javascript, see https://stackoverflow.com/questions/5753680/change-css-of-class-in-javascript. – Spangle Oct 23 '19 at 03:29
  • You can [target/change CSS vars with JS](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties#Values_in_JavaScript). Other CSS generally doesn't have a JS API, besides updating an element's `style` attribute. – Alexander Nied Oct 23 '19 at 03:31
  • Not 100% sure what you mean by that but if you mean the colours such as the ```:root{ --color1: White;``` that's in the CSS file – WildLifeRescuer Oct 23 '19 at 03:31
  • Is this link similar to what you looking for? "https://stackoverflow.com/a/15241958/1712016". Update css from js – phonemyatt Oct 23 '19 at 03:33

1 Answers1

1

document.documentElement.style.setProperty will do what you want

document.documentElement.style.setProperty('--colorText', 'black');
document.documentElement.style.setProperty('--colorBack', 'yellow');
:root {
    --colorText:Red;
    --colorBack:White;
}
body {
    color: var(--colorText);
    background-color: var(--colorBack);
}
<div>
Should be BLACK on YELLOW not RED on WHITE
</div>
Bravo
  • 6,022
  • 1
  • 10
  • 15