I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle
method in JavaScript. I'm puzzled as to why my code isn't producing the desired animation effect; could there be an error in my implementation?
const checkBox = document.querySelector('#checkBox');
const label = document.querySelector('#label');
function check() {
if (checkBox.checked) {
label.innerHTML = '<-<span>Un</span>Checked :)'
}
if (!checkBox.checked) {
label.innerHTML = '<-UnChecked :('
}
}
checkBox.addEventListener('click', check);
checkBox.click();
setInterval(() => {
checkBox.click();
label.classList.toggle('animation');
checkBox.classList.toggle('animation');
label.classList.toggle('animation2');
checkBox.classList.toggle('animation2');
setTimeout(() => {
checkBox.click()
label.classList.toggle('animation');
checkBox.classList.toggle('animation');
label.classList.toggle('animation2');
checkBox.classList.toggle('animation2');
}, 2000);
}, 4000);
* {
font-family: 'Cartograph CF';
}
#checkBox {
height: 20px;
width: 20px;
margin-right: 10px;
}
form {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 50px;
font-size: 30px;
}
label {
user-select: none;
}
.animation {
animation: fade .3s ease-in-out forwards;
opacity: 0;
}
.animation2 {
animation: fade .3s ease-in-out forwards;
opacity: 0;
}
span {
opacity: 0;
}
@keyframes fade {
form {
opacity: 0;
}
to {
opacity: 1;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<input type="checkbox" id="checkBox" class="animation">
<label for="checkBox" id="label" class="animation"><-UnChecked :(</label>
</form>
</body>
</html>