views:

23130

answers:

4

I need to make multiple divs move from right to left across the screen and stop when it gets to the edge. I have been playing with jQuery lately, and it seem like what I want can be done using that. Does anyone have or know where I can find an example of this?

+9  A: 

You will want to check out the jQuery animate() feature. The standard way of doing this is positioning an element absolutely and then animating the "left" or "right" CSS property. An equally popular way is to increase/decrease the left or right margin.

Now, having said this, you need to be aware of severe performance loss for any type of animation that lasts longer than a second or two. Javascript was simply not meant to handle long, sustained, slow animations. This has to do with the way the DOM element is redrawn and recalculated for each "frame" of the animation. If you're doing a page-width animation that lasts more than a couple seconds, expect to see your processor spike by 50% or more. If you're on IE6, prepare to see your computer spontaneously combust into a flaming ball of browser incompetence.

To read up on this, check out this thread (from my very first Stackoverflow post no less)!

Here's a link to the jQuery docs for the animate() feature: http://docs.jquery.com/Effects/animate

Jeremy Ricketts
One more note: Concurrent animations multiply the performance problem.
Jeremy Ricketts
If the div is positioned fixed then a smarter browser doesn't have to redraw the whole DOM-tree.
Georg
A fixed or absolution doesn't seem to matter for either FF3 or Safari 3. Whether the browser is redrawing the whole tree or not, I'm not sure. Either way, my CPU still jumps up about the same.
Jeremy Ricketts
+1 for bashing IE6
Oscar Kilhed
OMG! I didn't knew about performance problems with javascript animation! Thanks for the information.
lidermin
+3  A: 

In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

$("#startAnimation").click(function(){
    $(".toBeAnimated").animate({ 
        marginLeft: "+=250px",
    }, 1000 );
});

And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

Robert Grant
A: 

have a look at this demo - use jquery animation effect for moving a div

daniel