Reputation: 3941
I want to create a toggle button which when clicked needs to show the animation and when clicked again it should reverse the previous animation.
I have applied a class while the button is clicked using JS and it seems to be working fine. But after clicking again the second animation is not working and the animation definition is not displayed in devtools too.
const menu = document.getElementById('menu');
let isActive = false;
function onMenuClick(){
isActive = !isActive;
if(isActive){
menu.classList.add('active');
}
else{
menu.classList.remove('active');
}
menu.classList.remove('no-animation');
}
menu.addEventListener('click', onMenuClick);
.circle{
height: 2em;
width: 2em;
background: rebeccapurple;
border-radius: 50%;
animation: reverse 1s;
}
.active{
height: 4em;
width: 4em;
animation: active 1s forwards;
}
.no-animation{
animation: none !important;
}
@keyframes reverse{
0% {
background: red;
}
100% {
background: green;
}
}
@keyframes active{
0% {
background: green;
}
100% {
background: red;
}
}
@-webkit-keyframes reverse {
0% {
background: red;
}
100% {
background: green;
}
}
@-webkit-keyframes active {
0% {
background: green;
}
100% {
background: red;
}
}
<div class='circle no-animation' id='menu'></div>
Here the second animation reverse is not applied/shown in devtools.
Upvotes: 2
Views: 43
Reputation: 667
you can not name your animation reverse
, it is reserved keyword for css animation direction property... rename it and you are good to go.
const menu = document.getElementById('menu');
let isActive = false;
function onMenuClick() {
isActive = !isActive;
if (isActive) {
menu.classList.add('active');
} else {
menu.classList.remove('active');
}
menu.classList.remove('no-animation');
}
menu.addEventListener('click', onMenuClick);
.circle {
height: 2em;
width: 2em;
background: rebeccapurple;
border-radius: 50%;
animation: reversed 1s;
}
.active {
height: 4em;
width: 4em;
animation: active 1s forwards;
}
.no-animation {
animation: none !important;
}
@keyframes reversed {
0% {
background: red;
}
100% {
background: green;
}
}
@keyframes active {
0% {
background: green;
}
100% {
background: red;
}
}
@-webkit-keyframes reversed {
0% {
background: red;
}
100% {
background: green;
}
}
@-webkit-keyframes active {
0% {
background: green;
}
100% {
background: red;
}
}
<div class='circle no-animation' id='menu'></div>
Upvotes: 2