switch
by greg gorlen
HTML
<div class="switch">
<div class="slider">
</div>
</div>
CSS
body {
height: 95vh;
width: 95vw;
display: flex;
align-items: center;
justify-content: center;
}
.switch {
background-color: #4166ef;
width: 40px;
height: 20px;
border-radius: 15px;
}
.switch .slider {
position: relative;
top: 2px;
left: 2px;
width: 16px;
height: 16px;
border-radius: 50%;
background-color: #eee;
transition: all 0.2s ease;
}
.switch .slider-on {
left: 22px;
}
.switch .slider:hover {
background-color: #fff;
}
JavaScript
const switches = document.getElementsByClassName("switch");
for (let i = 0; i < switches.length; i++) {
switches[i].addEventListener("mousedown", e => {
if (switches[i].children[0].classList.contains("slider-on")) {
switches[i].children[0].classList.remove("slider-on");
}
else {
switches[i].children[0].classList.add("slider-on");
}
});
}