How to reverse an animation on mouse out after hover?
CSS Animations lets various elements on a web page to gradually change from one style to another. These make the website look more attractive and interesting reversing an animation means playing it backward.
Approach 1: This example illustrates reversing an animation using @keyframes from to @keyframes to and vice versa for reverse animation.
- Syntax:
elementSelector { animation-name: myanimation; } @keyframes myanimation { from { //code } to { //code } }element.classList.add("myclassname");
- Program:
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><title>animation</title><style>h1 {color: green;}.mystyle:hover {background-color: aqua;animation-name: myanimation;animation-duration: 2s;animation-fill-mode: forwards;}.mystyle {animation-name: reverse;animation-duration: 1s;}@keyframes myanimation {from {transform: rotate(0deg) scale(1);border-radius: 0px;}to {border-radius: 100px;transform: rotate(360deg) scale(0.7);}}@keyframes reverse {from {border-radius: 100px;transform: rotate(360deg) scale(0.7);}to {border-radius: 0px;transform: rotate(0deg) scale(1);}}</style></head><body><center><h1>GeeksforGeeks</h1><p>Animation and reverse animation</p><imgid="image"src=alt="image"width="260"height="260"class="alignnone size-full wp-image-1477785"onmouseover="myFunction()"/></center></body></html> - Output:

Approach 2: This example illustrates the use of transition property to create an animation effect on mouse hover and reversed animation on mouse out events.
- Program:
<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><title>animation</title><style>h1 {color: green;}.div1 {padding: 20px;background: green;border-radius: 0px;cursor: pointer;color: white;text-align: center;transition-duration: 5s;height: 100px;width: 200px;-webkit-transition: all 1s ease;-moz-transition: all 1s ease;-o-transition: all 1s ease;-ms-transition: all 1s ease;transition: all 1s ease;}.div1:hover {background: #ff7b29;border-radius: 30px;transform: scale(1.5);}</style></head><body><center><h1>GeeksforGeeks</h1><p>Animation and reverse animation</p><divclass="div1"><h3>A Computer Science Portal for Geeks</h3></div></center></body></html> - Output :



