Animations on iPad using Zepto.js
Since leaving TMG, I’ve been working on a couple of iPad projects. I’m finding the Zepto.js library to be a huge help. It is essentially a stripped down version of jQuery. It gives you chaining, selectors and a nice API, but because it is only aimed at Webkit loses all the cross-browser stuff you get in jQuery Mobile.
One of the main jobs in building things for the iPad is adding nice smooth transitions and animations. I thought that the best way to do this would be to toggle a CSS class using JavaScript,
$('div.animate').toggleClass('newposition'); |
and then use CSS transitions to animate the change.
div.animate { position: relative; left: 0; -webkit-transition: left 1s linear; } div.newposition { left: 500px; } |
This was horrid though. The animation worked, but it was jerky at best, with lots of the intermediate steps not being rendered. I found that I got a much better result by using the anim() function provided by Zepto.
$('div.animate').anim({translate3d: '500px,0,0'}, 1, 'linear'); |
This works by adding the animation as inline CSS, but that means any further changes and CSS rules get increasingly complicated. The method I’m using to solve this problem is to setup a clean up function and call that once the animation has completed.
var cleanup = function() { $('div.animate').toggleClass('newposition').attr('style',''); } $('div.animate').anim({translate3d: '500px,0,0'}, 1, 'linear',cleanup); |
This seems to work pretty well, but am I overcomplicating things? Have you found a better way to handle animations?