Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get smoother animation for sliding content with JavaScript/jQuery?

I have some content sliding here.

http://www.smallsharptools.com/downloads/jQuery/Slider/slider.html

The HTML structure is simple. There is an outer box with a fixed height and width with the overflow set to hidden. Then there is an inner container with the width set to the full width of the content inside of it which is a series of div elements marked with the Item class.

To slide the inner container left and right I am changing the left margin. To go left I reduce the value which becomes negative and to go back to the right I return it to zero. But I am seeing a jagged animation, even in Chrome which I expect would perform better.

My question is, would it be smoother if I used a different technique to move it back and forth? Would absolute positioning be smoother or is there something else I should consider? Are there any secrets do smooth animation that I just do not know yet?

like image 687
Brennan Avatar asked May 06 '09 00:05

Brennan


2 Answers

Margin would cause other elements to be recalculated because an element's margin affects the position of other elements around it.

Absolute positioning (on its own zIndex) would still cause repaints of other elements, but would be less costly in terms of calculating the objects around it.

This talk gives some good insight into how the browser/dom internals work

http://www.youtube.com/watch?v=a2_6bGNZ7bA&feature=channel_page

like image 137
Chad Grant Avatar answered Nov 14 '22 17:11

Chad Grant


I've had good results using the jQuery "Easing" plugin, documentation here.

This allows you to apply various smoothed movement such as a sine, bounce, elastic, accelerate and so on, to an html element.

It's using the same techniques you mention under the hood, but it takes care of the messy absolute/relative positioning for you. It' also cross browser and has been optimised over new versions.

One of best benefits of using easing however, is that it can help even low framerate animations look more impressive.

like image 4
Ash Avatar answered Nov 14 '22 19:11

Ash