0

If I would like to make an animation when a user hovers their mouse over an <a> tag, all I need is :hover.

However, if I want to do something when the user gets their mouse off of the <a>, the rules will apply. I do not want the animation to play before you hover, as in a { animation: name 1s linear reverse }, but I want it to play ONLY after the user stops hovering.

dale landry
  • 7,831
  • 2
  • 16
  • 28

3 Answers3

2

You can do this using javascript by adding a mouseover event on the element, then add a class on the event.target that has the animation attached to it. If you want this to be infinite, in terms of every time the user mouses out, then you can set a setTimeout and remove the class from the element using the same duration of your CSS animation.

//get the element from the DOM using its id attribute
const hoverme = document.getElementById('hoverme')

// create an event listener for mouseout  
// and pass the event into the function --> e
hoverme.addEventListener('mouseout', function(e) {
  // now get the current event.target --> e.target
  // and add the class that has the animation attached to it
  e.target.classList.add('anim-class')
  // remove the animation class using setTimeout
  // with a duration that is the same as that set in the 
  // css animation, in my example it is 2 seconds --> 2000ms
  setTimeout(()=>{
    e.target.classList.remove('anim-class')
  }, 2000) //<-- 2 seconds or 2000ms
})
#hoverme {
  color: #000;
}

#hoverme:hover {
  color: #0FF;
}

.anim-class {
  animation: rotate 2s ease-in-out;
}

@keyframes rotate {
  from {
    transform: rotate(360deg);
  }
  to {
    transform: rotate(0deg);
  }
}
<div id="hoverme">
  Hover over this
</div>
dale landry
  • 7,831
  • 2
  • 16
  • 28
0

A method without js would be to wrap the element you want to animate in a div and set that div to visibility: hidden by using a keyframes. Then set the animation for the same time as the actual animation for the element you are animating. This will hide the element during animation on initial load. Then you can use the :not selector to do what you want to animate it after every time you stop hovering.

#container {
  animation: hidden 1s linear 1;
}
#block {
  width: 50px;
  height: 50px;
  background: red;
  
}

div:not(:hover) {
  animation: grow 1s linear; 
}

@keyframes grow {
  to {width: 100px;}
}

@keyframes hidden {
  from {visibility: hidden;}
  to {visibility: hidden;}
}
<div id="container">
<div id="block"></div>
</div>
Justin
  • 2,873
  • 3
  • 9
  • 16
0

the opposite of hover is actually the initial state so you go like that

.class{
// not hover
}

.class:hover{
// when hover
}
Amir Saadallah
  • 668
  • 1
  • 8
  • 19