spaghetti_code
spaghetti_code

Reputation: 145

Rotating image 2 times

There is several questions about how to rotate an image, but I want an animation-like rotating. By an

event (tap) I would like to rotate an image with -5 degree then with 5 degree, but if I write both rotating in

the same function (or eventhandler), the first rotate doesn't appear only the second is visible.

$("#imgdiv").on('taphold', function(e){
    //$("#imageID").addClass("swing animated");
    $("#imageID").css({"transition-property":"transform","transition-duration":"2s","transform":"rotate(-5deg)"});
    $("#imageID").css({"transition-property":"transform","transition-duration":"2s","transform":"rotate(5deg)"});
    //$("#imageID").removeClass("swing animated");
});

I have also tried a swing animation with classes (addClass, then removeClass), but with the same result:

@keyframes swing { 
    25% { transform: rotate(-5deg); } 
    50% { transform: rotate(0deg); } 
    75% { transform: rotate(5deg); } 
    100% { transform: rotate(0deg); } 
} 

.swing { 
    transform-origin: top center; 
    animation-name: swing;
}

.animated { 
    animation-duration: 1s;  
    animation-fill-mode: both; 
    animation-timing-function: linear; 
}

Upvotes: 4

Views: 1219

Answers (2)

qtgye
qtgye

Reputation: 3610

You may put the second animation in a setTimeout in order to delay its animation until the first one finishes.

You can also put your transition in the css rather than in JS. Just place the transform value in JS.

Try something like this SAMPLE.

JS:

$(".clickme").click(function(){
  //animate to -5deg
    $(this).css('transform','rotate(-5deg)');
  //animate to 5deg
    setTimeout(function(){$(".clickme").css('transform','rotate(5deg)')},1000);
  //animate back to root position
 setTimeout(function(){$(".clickme").css('transform','rotate(0deg)')},2000);
});

Upvotes: 3

hitesh upadhyay
hitesh upadhyay

Reputation: 264

you can do with addclass and removeclass, but there is one mistake in your code. you are doing addclass and removeclass at the same time. so, animation is not happening or only one time happens so try setTimeout:

$("#imgdiv").on('click', function(e){
    $("#imageID").addClass("swing animated");
    setTimeout(function(){
        $("#imageID").removeClass("swing animated");
    },1000)
});

i have done that in jsfiddle - http://jsfiddle.net/tqn394k9/

Upvotes: 2

Related Questions