2

I have a div element, which has an animation to play when starting the page. I want to make it have another animation to play when I'm hovering over it. It works just fine, but when I get my mouse out of the div element, it plays the starting animation again (fades in from out of the screen).

@keyframes div{
   0%{
     opacity: 0;
   }
}
@keyframes divHover{
   50%{
      top: 200px;
   }
   100%{
      top: 0px;
   }
}
#div{
   opacity: 1;
   animation: div 1s;
   position: absolute;
   left: 0px;
   top: 0px;
}
#div:hover{
   animation: divHover 1s linear 0s infinite;
}
   <div id="div"> abc </div>

Expected: Div starts invisible and fades in. When hovering div, it goes up and down, and keeps doing it while hovering. After stopping the hover, div stops the animation and keeps its full opacity

Actual: After stopping the hover, div stops the animation but returns to 0 opacity, then takes one second to display the starting animation again.

https://jsfiddle.net/odq125Lu/6/

Temani Afif
  • 245,468
  • 26
  • 309
  • 415

2 Answers2

1

The issue is due to the fact that you are overriding the first opacity animation with the up & down one then when you unhover you active the first one again.

You can use multiple animations and consider animation-play-state to activate the second one:

@keyframes div {
  0% {
    opacity: 0;
  }
}

@keyframes divHover {
  50% {
    top: 200px;
  }
  100% {
    top: 0px;
  }
}

#div {
  opacity: 1;
  animation: 
    div 1s,
    divHover 1s linear 0s infinite;
  animation-play-state:running,paused;
  position: absolute;
  left: 0px;
  top: 0px;
  background:red;
  padding:20px;
}

#div:hover {
  animation-play-state:running,running;
}
<div id="div"> abc </div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • That kind of solved it. But what I actually want is for the div to go to its default. That "abc" cube should get back to the top at the moment I stop hovering it. I need the element to pause at 0% of the animation. – Prinzherbert Jun 10 '19 at 01:27
  • 1
    @Prinzherbert simply do the following in this case: https://jsfiddle.net/3ntj2e8L/ – Temani Afif Jun 10 '19 at 07:46
0

I'm no expert, but it may have something to do with the fact that you haven't set a 100% value for the animation "divHover"?

@keyframes div{
   0%{
     opacity: 0;
   }
   100% {
     opacity: 1;
   }
}
Zee
  • 145
  • 13