I am working on creating a switch button with CSS and JavaScript that needs an animation when toggling or clicked. The only issue I am facing is related to the animation.
I am wondering if there might be any problem with the positioning (relative, absolute)? Although I know that the css property left
can be animated, I am not sure why it's not working in this case.
(function (){
let
btn = document.querySelector ('.input-switch'),
container = document.querySelector ('.input-switch-container'),
checkbox = container.querySelector ('input[type="checkbox"]');
btn.addEventListener ('click', function (){
container.classList.toggle('active');
checkbox.checked ? checkbox.checked = false : checkbox.checked = true;
});
}())
*,
*::before,
*::after{
box-sizing: border-box;
}
.input-switch{
border-radius: .25rem;
width: 112px;
border: 1px solid #ddd;
overflow: hidden;
cursor: pointer;
user-select: none;
}
.input-switch-container {
position: relative;
display: flex;
transition: all 1.3s linear;
}
.input-switch-container.active{
left: -56px;
}
.input-switch-on,
.input-switch-off,
.input-switch-empty{
padding: .25rem 1rem;
line-height: 1.5;
flex: 0 0 50%;
}
.input-switch-on{
background-color: #007bff;
color: #fff;
}
.input-switch-off{
background-color: #f1f1f1;
}
.input-switch-empty{
background-color: #fff;
}
.input-switch input[type="checkbox"]{
opacity: 0;
}
<div class="input-switch">
<div class="input-switch-container">
<span class="input-switch-on">ON</span>
<span class="input-switch-empty"></span>
<span class="input-switch-off">OFF</span>
<input type="checkbox" />
</div>
</div>