mikegyi
mikegyi

Reputation: 45

Transition a linear animation on hover off

I'm trying to spin an SVG logo infinitely on hover like a vinyl on a record player and then slow down/ease out the animation when hovering off, like removing a needle from the player.

However, I can't work out how to make the smooth transition on hover off. Any ideas?

    @-webkit-keyframes spin { 
  100% { -webkit-transform: rotate(360deg); } 
}
@-moz-keyframes spin { 
  100% { -moz-transform: rotate(360deg); } 
}
@keyframes spin { 
  100% {  
  transform:rotate(360deg); 
  } 
}

transition: all 1s ease;

&:hover {
 -webkit-animation:spin 1s linear infinite;
 -moz-animation:spin 1s linear infinite;
  animation:spin 1s linear infinite;
}

Upvotes: 0

Views: 248

Answers (1)

VXp
VXp

Reputation: 12118

You can do it with the :not(:hover) pseudo-class pair, which fires the animation after the element is "unhovered", together with a wrapper element whose animation in the opposite direction (-) nullifies the one of the child on page load.

To avoid any visual deviations and inconsistencies the animation-timing-function of linear is used and recommended:

.vinyl {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: repeating-radial-gradient(#fff, #fff 1px, #000 1px, #000 2px);
}

.vinyl:hover {
  animation: spin 1s linear infinite;
}

@keyframes spin { 
  100% {transform: rotate(360deg)}
}

.vinyl:not(:hover) {
  animation: stop 2s ease-out;
}

@keyframes stop {
  100% {transform: rotate(360deg)}
}

span {
  display: inline-block; /* required */
  animation: nullify 2s ease-out;
  background: #ddd; /* just for demo */
}

@keyframes nullify {
  100% {transform: rotate(-360deg)}
}
<span>
  <div class="vinyl"></div>
</span>

Upvotes: 1

Related Questions