JSFiddle - React, Tailwind, and code Playground
HTML
<div id="theme">
Testing based on User OS level light/dark theme
</div>
<div class="option">
<span id="sun" class="lightCls" onclick="setLight();">Light</span>
<span id="moon" class="darkCls" onclick="setDark();">Dark</span>
<span>
<input type="checkbox" id="system" onclick="checkBox();" />
<label for="system">System Setttings</label>
</span>
</div>
CSS
* {
margin: 0;
padding: 0;
}
#theme {
width: 100%;
height: 100vh;
}
.default {
background: #ddd;
color: #000;
}
.dark {
background: #101010;
color: #fff;
}
.option {
position: absolute;
right: 0;
bottom: 0;
background: #fff;
border: 1px solid #ccc;
padding: 3px;
}
.lightCls, .darkCls {
padding: 2px;
cursor: pointer;
}
.lightCls {
background: #ddd;
color: #000;
}
.darkCls {
background: #101010;
color: #fff;
}
.addOpacity {
opacity: 0.2;
pointer-events: none;
}
JavaScript
function defaultFunction() {
localStorage.setItem('option', 'default');
localStorage.setItem('systemOption', false);
}
defaultFunction();
function myFunction() {
let getOption = localStorage.getItem('option');
let themeDiv = document.getElementById('theme');
if(localStorage.getItem('systemOption') == 'true') {
let osTheme = window.matchMedia('(prefers-color-scheme: dark)');
osTheme.addEventListener('change', event => {
if(event.matches) {
themeDiv.classList.add("dark");
themeDiv.classList.remove("default");
} else {
themeDiv.classList.add("default");
themeDiv.classList.remove("dark");
}
})
} else {
if(getOption == 'dark') {
themeDiv.classList.add("dark");
themeDiv.classList.remove("default");
} else if(getOption == 'default') {
themeDiv.classList.add("default");
themeDiv.classList.remove("dark");
}
}
}
myFunction();
function setDark() {
localStorage.setItem('option', 'dark');
myFunction();
}
function setLight() {
localStorage.setItem('option', 'default');
myFunction();
}
function checkBox() {
let cBox = document.getElementById('system');
let sun = document.getElementById('sun');
let moon = document.getElementById('moon');
if(cBox.checked) {
localStorage.setItem('systemOption', true);
sun.classList.add('addOpacity');
moon.classList.add('addOpacity');
} else {
localStorage.setItem('systemOption', false);
sun.classList.remove('addOpacity');
moon.classList.remove('addOpacity');
}
myFunction();
}