13

On mouse over, I need to rotate an element counterclockwise 180˚ over an interval of 150ms, and then on mouse out I need to rotate the element counterclockwise back to the original 0˚ over 150ms.

I am open to using CSS3, jQuery, and JavaScript.

I use Chrome, but I also need to make it work for Firefox and Safari. Not too worried about IE.

chharvey
  • 8,580
  • 9
  • 56
  • 95
  • Why 150ms? Just know that when working with the browser time, you will never hit an exact mark, but using `setTimeout(functionCall(),150)` would be what you need. – vol7ron Feb 25 '12 at 04:34
  • Which type of elements? Only images? – Julien Bourdon Feb 25 '12 at 04:34
  • Well CSS3 will only happen if you want to use the *experimental* [transform property](https://developer.mozilla.org/en/CSS/transform) and [transition property](https://developer.mozilla.org/en/CSS/transition), which can sometimes be a bit slow in Firefox (just to note). – animuson Feb 25 '12 at 04:35
  • See the highest answer to [this question](http://stackoverflow.com/questions/382591/rotating-a-div-element-in-jquery), works in Chrome, Firefox and Safari but not IE. – DNJohnson Feb 25 '12 at 04:43
  • @vol7ron: I chose 150 as a number I could identify and possibly change later if needed. @Julien Bourdon: An arbitrary block element. A `div` would be just fine. – chharvey Feb 25 '12 at 04:54

1 Answers1

22

Use CSS3 transform, transition and Javascript to add/remove classes.

Demo: http://jsfiddle.net/ThinkingStiff/AEeWm/

HTML:

<div id="rotate">hover me</div>

CSS:

#rotate {
    border: 1px solid black;
    height: 100px;
    width: 100px;
}

.over {
    transform: rotate( -180deg );            
    transition: transform 150ms ease;
}

.out {
    transform: rotate( -360deg );            
    transition: transform 150ms ease;
}
​

Script:

var rotate = document.getElementById( 'rotate' );

rotate.addEventListener( 'mouseover', function () {

    this.className = 'over';

}, false );

rotate.addEventListener( 'mouseout', function () {

    var rotate = this;

    rotate.className = 'out';
    window.setTimeout( function () { rotate.className = '' }, 150 );

}, false );

​
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239