Back
A detailed tutorial on crafting an elegant toggle switch complete with fluid animations and customizable options.
<div class="toggle-container">
<input type="checkbox" id="toggle" class="toggle">
<label for="toggle" class="toggle-label">
<span class="toggle-button"></span>
</label>
</div>
.toggle-container {
display: flex;
align-items: center;
padding: 10px;
}
.toggle {
display: none;
}
.toggle-label {
position: relative;
width: 60px;
height: 30px;
background-color: #aaa;
border-radius: 50px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.toggle-button {
position: absolute;
top: 2px;
left: 2px;
width: 26px;
height: 26px;
background-color: #fff;
border-radius: 50%;
transition: left 0.3s ease;
}
.toggle:checked + .toggle-label .toggle-button {
left: 32px;
}
document.getElementById('toggle').addEventListener('change', function(event) {
const toggle = event.target;
const toggleLabel = document.querySelector('.toggle-label');
if (toggle.checked) {
toggleLabel.style.backgroundColor = '#32ffcc';
} else {
toggleLabel.style.backgroundColor = '#aaa';
}
});
<div class="toggle-container">
<input type="checkbox" id="toggle" class="toggle">
<label for="toggle" class="toggle-label">
<span class="toggle-button"></span>
</label>
</div>
<script>
document.getElementById('toggle').addEventListener('change', function(event) {
const toggle = event.target;
const toggleLabel = document.querySelector('.toggle-label');
if (toggle.checked) {
toggleLabel.style.backgroundColor = '#32ffcc';
} else {
toggleLabel.style.backgroundColor = '#aaa';
}
});
</script>
<style>
.toggle-container {
display: flex;
align-items: center;
padding: 10px;
}
.toggle {
display: none;
}
.toggle-label {
position: relative;
width: 60px;
height: 30px;
background-color: #aaa;
border-radius: 50px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.toggle-button {
position: absolute;
top: 2px;
left: 2px;
width: 26px;
height: 26px;
background-color: #fff;
border-radius: 50%;
transition: left 0.3s ease;
}
.toggle:checked + .toggle-label .toggle-button {
left: 32px;
}
</style>
Thank you for reading this article.
Comments
No comments yet. Be the first to comment!