I have a keyframe and 2 buttons. When clicking on the forward button, I want my box to move forwards and when clicking on the back button, I want to reverse my keyframe, so the box should move back.
This is what I have tried:
const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
box.classList.add('active');
});
document.getElementById('left').addEventListener('click', () => {
box.style.animationDirection = 'reverse';
// Also tried it with: box.classList.remove('active');
});
.box {
width: 100px;
height: 100px;
background: blue;
position: relative;
}
.active {
animation: move 1s forwards;
}
@keyframes move {
from {
left: 0;
}
to {
left: 20px;
}
}
<button id="left"><</button>
<button id="right">></button>
<div ></div>
CodePudding user response:
You could use two different animations assigned to two different classes and just add and remove them like a pseudo toggle
const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
box.classList.remove('moveLeft');
box.classList.add('moveRight');
});
document.getElementById('left').addEventListener('click', () => {
box.classList.remove('moveRight');
box.classList.add('moveLeft');
});
.box {
width: 100px;
height: 100px;
background: blue;
position: relative;
}
.active {
animation: move 1s forwards;
}
.moveRight {
animation: moveRight 1s forwards;
}
.moveLeft {
animation: moveLeft 1s forwards;
}
@keyframes moveRight {
from {
left: 0;
}
to {
left: 20px;
}
}
@keyframes moveLeft {
from {
left: 20px;
}
to {
left: 0px;
}
}
<button id="left"><</button>
<button id="right">></button>
<div ></div>
You could use a transition as well if you're not set on using keyframes. Same result, two different methods
const box = document.querySelector('.box');
document.getElementById('right').addEventListener('click', () => {
box.classList.add('active');
});
document.getElementById('left').addEventListener('click', () => {
box.classList.remove('active');
});
.box {
width: 100px;
height: 100px;
background: blue;
position: relative;
transition: all 1s ease-in-out;
}
.active {
transform: translateX(20px);
transition: all 1s ease-in-out;
}
<button id="left"><</button>
<button id="right">></button>
<div ></div>