Triggering animation by changing the elemet classList

Hello there. I want to first apologize for my grammar.
I have 2 css animations. One is called ‘expand’, and it has to trigger when the mouse enters the element, and one named ‘contract’ which triggers when the mosuse leaves the element.
The way I am trying to do it is by changing the elements classList with javascript, but it only works once.The animation gets triggered only the first time and never again.
Am I missing something fundamental?
Here is a link to the code pen I’ve done. The code is only 12 lines long, and its easier to see it than read about it :smiley:

I was able to make it run properly by adding another animation for the contract class. So, instead of playing the same animation in different directions I declared two different animations.

Welcome, Bulgarian.

You have almost done it. Just remember that there is also an onmouseout event:

Just reuse the function, but with a different event, and reassign the class to the original class, when the mouse moves off of the element.

Hope this helps

Keep in mind that mouse-in and mouse-out events don’t work on mobile, since there is no concept of a mouse pointer to begin with. For visual effects, it’s fine, but don’t make functionality depend on it.

Thanks for your help. I made a second animation, and also fixed the shorthand animation property(I really need to memorize it :D). Now the expand animation works properly, but I cant fix the contract animation. Did you manage to make both animations work?
I think that the problem is in the scale() property, it doesn’t change the size. I added a color change and the color changes after the mouse leaves, but the element does not scale.

Also if the cursor leaves the element before the scaling reaches 4 the animation will probably jump to 4 and go down to one. Is there a way to check the state of animation, or somehow make it play backwards from where it currently is ?

Thanks, I will remember that!
Making fully working websites is still far away for me, especially mobile friendly ones.I still have much to learn.

Both animation works. I took another look at your code and it’s a typo that is causing the bug. In the contract animation, the transform property is written “transfomr” in the 0% block.

And for the matter of the cursor leaving the element before the animation ends, what is happening is that the second animation is starting and it starts as defined at 0% with transform: scale(4);and that causes it to skip the scaling. As far as I’m aware of, you cannot find a way around it with css animations. You can use some logic in your code to guarantee that the element’s class doesn’t change before the animation is complete, even if mouseleave is triggered. But that seems quite complicated to me.