Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS animation - Rotate 45 degrees further on each hover

I want to have an element that rotates 45 degrees, when the site is shown (that is working fine), but I also want the element to rotate 45 degrees further every time it is hovered over. The element, should not revert back at any time. How do I achieve that using CSS animation?

I have created a fiddle that that makes the first animation, but I simply can't make it rotate 45 degrees more each time it is hovered over.

My HTML:

<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">

My CSS:

.image {
position: absolute;
top: 50%;
left: 50%;
width: 120px;
height: 120px;
margin:-60px 0 0 -60px;
-webkit-animation:spin 0.6s linear;
-moz-animation:spin 0.6s linear;
animation:spin 0.6s linear;
animation-fill-mode: forwards;
}

@-moz-keyframes spin { 100% { -moz-transform: rotate(45deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(45deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(45deg); transform:rotate(45deg); } }
like image 986
christian24 Avatar asked Mar 09 '23 16:03

christian24


2 Answers

I can't find a way to answer your question with pure CSS. If you are open to using jQuery here is a potential solution for you...

jsfiddle

var image = $('#spin');
var r = 45;

$(function() {
  image.css({
    'transform': 'rotate(' + r + 'deg)'
  });

  jQuery.fn.rotate = function(degrees) {
    $(this).css({
      'transform': 'rotate(' + degrees + 'deg)'
    });
  };

  image.mouseover(function() {
    r += 45;
    $(this).rotate(r);
  });
});
.image {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 120px;
  height: 120px;
  margin: -60px 0 0 -60px;
  transition: all 0.6s ease-in-out;
  transform: rotate(0deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="spin" class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
like image 174
sol Avatar answered Mar 12 '23 04:03

sol


Try using JavaScript's onmouseenter, so when the mouse enters the element it does something, in this case rotating 45 degrees. Here's the jQuery way: https://api.jquery.com/mouseenter/

//use library: http://jqueryrotate.com/

$('.image').mouseenter(function () {
    $(this).rotate(45);
});
like image 45
broodjetom Avatar answered Mar 12 '23 06:03

broodjetom