You can actually do this without ANY Javascript or jQuery by taking advantage of the magic of CSS3 Transitions and Transforms.
First, you need to set your div
to have a rotation of zero degrees by setting the transform
attribute like so:
div {
transform:rotate(0deg);
}
Then, you just need the hover-based transition (aka, the spin effect). To do that, you can use the :hover
pseudo element, like so:
div:hover {
transition: transform 1s ease;
transform: rotate(360deg);
}
If you would like the element to have a transition where it spins back in place, simply add the transition attribute to the CSS for div
, like so:
div {
transform:rotate(0deg);
transition: transform 1s ease;
}
Of course, the timing of 1s
is totally up to you; feel free to use any value you want, even ms
(for milliseconds).
Here's some more information on CSS3 Transitions and Transforms:
And here's an example of this kind of rotation in action: http://www.w3schools.com/css/tryit.asp?filename=trycss3_transition2.
As for compatibility, it is supported by about 76% of the average browser market: http://caniuse.com/#search=transitions
Note that some browsers don't support the transition
property as is; some require you to use a vendor prefix for support. For example, Chrome and Safari have the prefix -webkit-
, so you would put -webkit-transition: transform 1s ease;
to make it work in those browsers. I have listed the vendor prefixes below:
- Chrome/Safari:
-webkit-
- Opera:
-o-
- Firefox:
-moz-
- Internet Explorer:
-ms-