I am trying to make some sidebar animations using css, react, material ui.
I have an image that when clicked slides to the left, and when clicked again will slide to the right. So far I have only succeeded in creating an animation where the image slides to the left, and after some time slides back to the right. I cannot get the animation to slide back to the right with a second click, only once the first animation finishes playing can it be clicked again.
below is the react and material components creating space for an image to slide left and right
const Portfolio = ({menuOpen, setMenuOpen}) => {
const [counter, setCounter] = useState(0);
const animate = () => {
setMenuOpen(true);
setTimeout(() => {
document.getElementById("box").classList.add('PortfolioRightImg2');
document.getElementById("box").classList.remove('PortfolioRightImg');
setTimeout(() => {
setMenuOpen(false);
}, 3000);
}, 3000);
}
...
<Grid container className='PortfolioGrid' sx={{display: 'relative'}}>
<Grid item xs={6} className='PortfolioLeft'>
hello
</Grid>
<Grid item xs={6} className='PortfolioRight'>
<Box
onClick={animate}
id= 'box'
className={menuOpen ? 'PortfolioRightImg active' : 'PortfolioRightImg'}
component="img"
alt="The house from the offer."
src={img}
/>
</Grid>
</Grid>
and here is the css
.PortfolioGrid{
background-color: aquamarine;
.PortfolioLeft{
background-color: bisque;
}
.PortfolioRight{
background-color: rgb(205, 255, 220);
.PortfolioRightImg{
height: calc(100vh * 3/12);
width: calc(100vw * 2/12);
&.active{
position: relative;
animation: slide 3s forwards;
}
}
.PortfolioRightImg2{
height: calc(100vh * 3/12);
width: calc(100vw * 2/12);
&.active{
position: relative;
animation: slide2 3s forwards;
}
}
}
}
@keyframes slide {
0% {left:0px; top:0px;}
100% {left:calc((100vw * 2/12)*(-1));}
}
@keyframes slide2 {
0% {left:calc((100vw * 2/12)*(-1));}
100% {left:0px; top:0px;}
}
Essentially when the image is clicked, once the sliding animation to the left finishes the className is changed to the one with the right sliding animation. Once the right sliding animation finishes, the state of menuOpen variable is changed to false so that clicking the image can once again change the state to being true. The problem is I am changing the className of the image based on a hardcoded timer for now. Any help is greatly appreciated, and let me know what else I can provide!