How do I rotate an element to 180 deg over 150 ms on hover?

27,837

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 );

​
Share:
27,837
chharvey
Author by

chharvey

Front-end engineer with a focus on user accessibility and reusable modular design patterns.

Updated on July 09, 2022

Comments

  • chharvey
    chharvey almost 2 years

    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.