I am trying to build an animation on a button. The button contains three parts: before, center, and after. The before and after parts contain a “+” symbol, while the center part contains some text. Initially, the before part is hidden (width: 0, height: 0).
When the mouse enters the button, the before part should be displayed and the after part should be hidden, following the animation described below.
On the mouseenter event, the before part zooms in while rotating 90 degrees over one second, which pushes the center part to the right. At the same time, the after part zooms out while rotating -90 degrees until it disappars. On mouseleave, everything should return to the initial state.
I have successfully implemented the mouseenter animation, but I am unable to reverse it back to the original state.
HTML
+
+
CSS
/* PRIMARY BUTTON */
.primary-btn-anchor {
text-decoration: none;
}
.primary-btn_wrapper {
margin: 100px;
width: 250px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
background-color: #000;
}
.primary-wrapper-btn {
width: 195px;
height: 100%;
}
.wrapper_after, .wrapper_before {
width: 50px;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
font-size: 1.3rem;
color: var(--primary-btn-color);
background-color: var(--primary-btn-bg);
cursor: pointer;
}
.wrapper_before {
width: 0px;
height: 100%;
margin: 0;
}
.wrapper_after {
margin: 0 0 0 5px;
}
.wrapper-btn {
padding: 0 12px;
color: var(--primary-btn-color);
font-size: 14px;
line-height: 2rem;
text-transform: uppercase;
background-color: var(--primary-btn-bg);
border: none;
cursor: pointer;
}
JS
let btnBoxes = window.document.querySelectorAll(".primary-btn_box");
btns.forEach(function(el) {
// Animation on mouse enter
el.addEventListener("mouseenter", function(){
btns[0].style.marginRight = "5px";
btns[0].style.animationName = "btnRotateIn";
btns[0].style.animationDuration = "1s";
btns[0].style.animationFillMode = "forwards";
btns[2].style.marginLeft = "0px";
btns[2].style.animationName = "btnRotateOut";
btns[2].style.animationDuration = "1s";
btns[2].style.animationFillMode = "forwards";
})
// Animation on mouse leave
el.addEventListener("mouseleave", function(){
btns[0].style.marginRight = "0px";
btns[0].style.animationName = "btnRotateOut";
btns[0].style.animationDuration = "1s";
btns[2].style.marginLeft = "5px";
btns[2].style.animationName = "btnRotateIn";
btns[2].style.animationDuration = "1s";
})
})