CSS prefers-color-scheme Override Toggle with JS

Hi, I’m coding my first static website. I used CSS Variables on my sytlesheet file to define colors. Like,

:root { 
--bg-color: #fff;
--txt-color: #000;
}

@media (prefers-color-scheme: dark) {
:root {
--bg-color: #000;
--txt-color: #fff;
}
}

body {
background-color: var(--bg-color);
color: var(--txt-color);
}

I assume that the user who has dark theme on it’s operation system would already choose dark mode so it’s perfectly okay at this state. But I want to provide an <input type:"checkbox"> to let the user switch between themes if they want to. Unlike most other guides on the internet, I do not want to save user preferences on browser’s localstorage because of my assumption. And I’m a total newbie at JS. So, I’d be appreciated if anyone can give me the code with explanation.

Hi, i was able to find 2 basic guides which can show you how to create a toggle switch button, using checkbox. Their CSS styling is quite extensive, but you can wipe big part of it, if it doesnt suite your needs.

This only goes over the HTML and CSS styling, but not the JS logic:

Here the top answer presents how to attach a JS behavior:

Lastly, this is my solution to the FCC Pomodoro Timer Project, there i implemented a switch button, using the w3school sources, but putting my own flavor to it. Its done with React, so idk if it will be of good help to you, but its a good example on how it could look:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.