nizzle
nizzle

Reputation: 1046

css transition initial value

I would like to animate a div from right to left.

I cannot use a stylesheet because I don't know the amount of px.

If I set the initial value (where the animation starts from) and the end-value in the same function, it doesn't work.

//DOES NOT WORK
$("#hi").css({"width" : "200px", "transform" : "translateX(500px)"});
$("#hi").css({"transition" : "all 5s ease-out", "transform" : "translateX(0px)"});

//WORKS
$("#alsohi").css({"width" : "200px", "transform" : "translateX(500px)"});
setTimeout(function(){
    $("#alsohi").css({"transition" : "all 5s ease-out", "transform" : "translateX(0px)"});
}, 50);

as you can see in this fiddle: http://jsfiddle.net/c66Fb/

what is a better solution to this than using a timeout?

Upvotes: 1

Views: 3384

Answers (1)

mifi79
mifi79

Reputation: 1106

It is because both of the $("#hi") css changes are executed simultaneously, an easy way to make the first example work would be to check that the CSS properties you are setting in the first statement are actually set:

$("#hi").css({"width" : "200px", "transform" : "translateX(500px)"});

if ($("#hi").css("width") === "200px") {
    $("#hi").css({"transition" : "all 5s ease-out", "transform" : "translateX(0px)"});
}

You can see an example of this working at: http://jsfiddle.net/mifi79/c66Fb/1/

Another hacky way to accomplish this would be to use a while loop to do the check:

$("#hi").css({"width" : "200px", "transform" : "translateX(500px)"});
while ($("#hi").css("width") !== "200px") { return false; }
$("#hi").css({"transition" : "all 5s ease-out", "transform" : "translateX(0px)"});

The Fiddle for that one is here: http://jsfiddle.net/mifi79/c66Fb/2/

Another option (and possibly the better option from a compatibility point of view) would be to use jQuery's .animate() method, which would work with browsers that don't support CSS transforms (IE prior to 9)

Upvotes: 1

Related Questions