Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rotate an image by a random amount using CSS?

I have a gallery of 20 images on my web page that I would like to rotate by a random amount (-5 to 5 degrees) upon hover over each image. If possible, I'd like to use just CSS. If not, I would be open to using JavaScript or jQuery.

My CSS is as follows:

.photo:hover {
    z-index:1;
    transform:rotate(6deg) scale(1.25);
    -webkit-transform:rotate(6deg) scale(1.25);
    -moz-transform:rotate(6deg) scale(1.25);
    -ms-transform:rotate(6deg) scale(1.25);
}

6deg should be a random number, so every time the user hovers over an image, it rotates by a random amount between -5 and 5. Can I call a JavaScript function from within the CSS, or even a JavaScript variable? That would be better than creating 20 different CSS ids.

How can I accomplish this? Thanks!

like image 282
Jordan H Avatar asked Nov 22 '12 01:11

Jordan H


1 Answers

You won't need separate CSS IDs, but you could use some jQuery on the class. .each() is used instead of .css() directly here because otherwise the random angle would be generated once and used for all of the images. To rotate individally on hover:

$('.photo').hover(function() {
    var a = Math.random() * 10 - 5;
    $(this).css('transform', 'rotate(' + a + 'deg) scale(1.25)');
}, function() {
    $(this).css('transform', 'none');
});

If you want to smoothly animate these transformations, you can simply add a transform CSS property to the class:

.photo {
    transition: transform 0.25s linear;
}

Demonstration: http://jsbin.com/iqoreg/1/edit

like image 174
Delan Azabani Avatar answered Sep 28 '22 13:09

Delan Azabani