Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger CSS transform with jQuery more than once

I have some code that successfully rotates a div how I'd like, however, it is only doing it once. I'm assuming this is because the function simply adds the CSS transform properties and once they are added, the browser (I'm using Chrome on Win7) doesn't care if they are added a second time. Is there a way to have the div rotate every time I click, rather than just once?

jQuery

$(function(){
    $('.hanging-div').on('click', function(){
        $(this).css({
            'transform':'rotate(-360deg)',
            '-ms-transform':'rotate(-360deg)',
            '-moz-transform':'rotate(-360deg)',
            '-o-transform':'rotate(-360deg)'
        });
    });
});

HTML

<div class="hanging-div"><img src="http://placehold.it/65x350"></div>

CSS

.hanging-div {
    margin:0 auto;
    display:block;
    width:200px;
    padding:50px 0;
    transition:all 2s;
    -moz-transition:all 2s;
    -webkit-transition:all 2s;
    -o-transition:all 2s;
    transform-origin:50% 0%;
    -moz-transform-origin:50% 0%;
    -webkit-transform-origin:50% 0%;
    -ms-transform-origin:50% 0%;
    -o-transform-origin:50% 0%;
}

And here is the fiddle: http://jsfiddle.net/MrP43/1/

EDIT

I've also tried removing the transform property afterwards, but it doesn't seem to have an effect.

$(function(){
    $('.hanging-div').on('click', function(){
        $(this).css({
            'transform':'rotate(-360deg)',
            '-ms-transform':'rotate(-360deg)',
            '-moz-transform':'rotate(-360deg)',
            '-o-transform':'rotate(-360deg)'
        }, function(){
                $(this).css({
                    'transform':'',
                    '-ms-transform':'',
                    '-moz-transform':'',
                    '-o-transform':''
                });
        });
    });
});
like image 615
Dryden Long Avatar asked Nov 17 '25 22:11

Dryden Long


1 Answers

Ok, I've figured it out thanks to @GroundZero. I simply made the degree of rotation a variable and subtracted 360 degrees from that variable for each click and now it works as expected. Now I wonder if this is the best way to go about doing this? It works, so I'm not complaining, but if anyone else has any solutions, I'd love to see them. Thanks!

$(function(){
    n = -360;
    $('.hanging-div').on('click', function(){
        $(this).css({
            'transform':'rotate('+n+'deg)',
            '-ms-transform':'rotate('+n+'deg)',
            '-moz-transform':'rotate('+n+'deg)',
            '-o-transform':'rotate('+n+'deg)'
        });
        n-=360;
    });
});

Fiddle: http://jsfiddle.net/tuJjg/

like image 100
Dryden Long Avatar answered Nov 19 '25 11:11

Dryden Long



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!