JSFiddle - React, Tailwind, and code Playground
HTML
<body onload='checkCookie()'>
<div style='padding: 10px 0 10px 0; margin-bottom: 10px; background: rgba(0,0,0,0.05);'>
<div class='mode'><input class='mode__i' id='mode' name='check' type='checkbox'/>
<label class='mode__l' for='mode'/>
</div>
</div>
</body>
CSS
:root {
--light: #f4f7f6;
--dark: #2b2b2b;
--trueback: #339989;
--falseback: #d9dbdc;
--text: var(--dark);
--bg: var(--light);
--styleback: var(--falseback);
}
body {
background: var(--bg);
color: var(--text);
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
}
.mode {
display: block;
margin-left: 100px;
}
.mode__i {
display: none;
}
.mode__l {
display: block;
position: relative;
width: 50px;
height: 28px;
margin: 0 auto;
border-radius: 20px;
background: var(--styleback);
-webkit-box-shadow: 0 0 1px 0 rgba(0,0,0,0.25);
-moz-box-shadow: 0 0 1px 0 rgba(0,0,0,0.25);
box-shadow: 0 0 1px 0 rgba(0,0,0,0.25);
}
.mode__l::before {
position: absolute;
top: 0;
left: calc(50% - 20px);
width: 20px;
height: 20px;
margin: 4px;
transform: translateX(-5px);
transition: all 300ms;
border-radius: 20px;
background: white;
content: '';
z-index: 1;
cursor: pointer;
-webkit-box-shadow: 1px 1px 3px 0 rgba(0,0,0,0.3);
-moz-box-shadow: 1px 1px 3px 0 rgba(0,0,0,0.3);
box-shadow: 1px 1px 3px 0 rgba(0,0,0,0.3);
}
.mode__l::after {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: var(--text);
font-size: 14px;
margin-left: -80px;
content: 'Modo noturno';
}
.mode__i:checked + label::before {
transform: translateX(17px);
}
JavaScript
var mode = document.getElementById('mode');
var body = document.body;
mode.addEventListener('change', function() {
if(mode.checked == true) {
localStorage.estilo = "2"; // valor para layout escuro
body.style.setProperty('--bg', 'var(--dark)');
body.style.setProperty('--text', 'var(--light)');
body.style.setProperty('--styleback', 'var(--trueback)');
}
else {
localStorage.estilo = "1"; // valor para layout claro
body.style.setProperty('--bg', 'var(--light)');
body.style.setProperty('--text', 'var(--dark)');
body.style.setProperty('--styleback', 'var(--falseback)');
}
});
function checkCookie() {
$(window).on("load",function(){
if(localStorage.estilo == "2"){
$("#mode").trigger("click");
}
});