I want my div to return to its original position in reverse right after I stop hovering. But the return starts before I even begin to hover on the div and right after running the code.
I need the reverse animation to be performed only after I stop hovering.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<style>
div {
width: 100px;
height: 100px;
padding: 2px;
background-color: lightblue;
color: White;
font-size: 40px;
text-align: center;
vertical-align: middle;
display: table-cell;
}
div:hover {
animation: moveDiv 10s linear infinite;
animation-play-state: running;
}
div:not(:hover) {
animation: moveDiv 3s reverse ease-in;
}
@keyframes moveDiv {
0% {
transform: translate(0px, 0px);
}
25% {
transform: translate(250px, 180px);
background: yellow;
}
50% {
transform: translate(490px, 60px);
background: lightseagreen;
}
75% {
transform: translate(550px, 390px);
background: crimson;
}
100% {
transform: translate(600px, 450px);
background: orchid;
}
}
</style>
<body>
<div>hello</div>
</body>
</html>
2
Answers
Is
div:not(:hover)
triggering the reverse animation right after the page loads? Try addinganimation-direction: reverse;
todiv:not(:hover)
.The easiest is probably to use some JS and the Web Animations API. You’d listen for the pointer events, and then control your animation status from there.
Since you want two different durations for the forward animation and the backward one, we need to add some trickery involving setting the playback-rate of our animation:
For a simpler case of the same speed animations in both ways, we could have used
Animation#reverse()
: