Crashalot
Crashalot

Reputation: 34523

Translate element by constant amount with CSS for smoother animation?

Is it possible to translate an element by a constant amount with CSS? For instance, we want to move a div in 50 pixel increments up the screen. Right now, we use update the translate value manually, but this creates a choppy effect.

Here's the code, where translate equals a value that increments by 50 every time this line is called:

$(element).css( '-webkit-transform', 'translate3d( 0, ' + translate + 'px, 0)' );

We need this work on mobile devices so we can't use jQuery animate because it is not smooth enough (in our experience) on mobile. We need to translate by a constant amount because we need to track the element's position so we call the translate code every X ms.

Upvotes: 1

Views: 1224

Answers (2)

robertc
robertc

Reputation: 75757

Instead of constantly firing off repeated animations I'd just set one animation with appropriate values, then detect the current position in your loop rather than trying to do the animation in it. This updated example from the linked question seems to indicate it would work.

You may want to interrogate the transform property to get the current translation values if they're going to be more complex than simple top/left. You should get a value that looks something like this:

matrix(1, 0, 0, 1, 0, 300)

Upvotes: 1

Trader
Trader

Reputation: 249

There are several jQuery plugins that extend the animate method to use CSS3 and make animations very smooth on mobile devices.

I've used in the past a couple of plugins, don't remember the ones I used, but a quick Google search gave me this one:

http://ricostacruz.com/jquery.transit/

It would be something like this:

$(element).transition({ y: '+=50' });

Upvotes: 0

Related Questions