Brennan
Brennan

Reputation: 11686

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?

Upvotes: 10

Views: 9988

Answers (2)

Chad Grant
Chad Grant

Reputation: 45422

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

Upvotes: 7

Ash
Ash

Reputation: 62145

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.

Upvotes: 4

Related Questions