jquerycsswordpressrandomtilt

Trying to tilt multiple divs to different, random angles


I'm trying to achieve the opposite of what is described here.

I have a series of divs in a wordpress page, which I would like to appear on the page as each randomly tilted to a different slight degree.

They should also be straightened up as the user hovers on them.

Here's what I have:

    (function($) {
    $( document ).ready(function() {
        var a = Math.random() * 10 - 5;
        $('.format-aside').each(function( index ) { 
            $(this).css('transform', 'rotate(' + a + 'deg)');})
        });
})(jQuery);

at first, I skipped the .each part, but this resulted in all the divs being tilted the same way. However even with the .each they still end up tilted the same way.

As to the hover effect, I have set it in the CSS page:

.format-aside:hover{-ms-transform: rotate(0deg); 
-webkit-transform: rotate(0deg); 
transform: rotate(0deg);}

and it worked when all of this was done in CSS (but of course then all divs tilted the same way). Now it doesn't work anymore so I figure I should add the hover effect in jQuery?


Solution

  • The reason they're all tilted the same amount is because you calculate the degree before iterating over the elements. Instead, you should calculate one angle per element:

    (function($) {
    $( document ).ready(function() {
        $('.format-aside').each(function( index ) { 
            // rotation degree between -5 and 5
            var a = Math.random() * 10 - 5;
            $(this).css('transform', 'rotate(' + a + 'deg)');})
        });
    })(jQuery);
    

    As for the hover effect try adding the !important option to them:

    .format-aside:hover {
        -ms-transform: rotate(0deg) !important;
        -webkit-transform: rotate(0deg) !important;
        transform: rotate(0deg) !important;
    }
    

    The reason for your CSS not working is because jQuery applies the rules on the elements as in-line styles. These are higher priority than any CSS selectors. Using the !important rule you can override that.