Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery 'Choppy' animation - simple test case

Here's a simple test case for animating a Div using absolute positioning and jQuery.

<html>
<head>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js'></script>
    <script type='text/javascript'>
        function slide(){
            $('#box').animate({'left': 0},3000);
        }   
    </script>
</head>
<body>
    <button onclick="slide()">slide</button>
    <div id="box" style="position: absolute; width: 120px; height: 100px; background: #ff0000; left: 500px"></div>
</body>

In Firefox 4 (on mac) the animation 'tears' and is very stuttery. In Safari and Chrome it is better, but still has visible juddering.

Having simplified the problem down to the above test case, I'm not really sure where to go next. Is this a jQuery bug? Am I missing something with the absolute positioning that would cause the browser to redraw loads? Would be incredibly grateful if some people could try the code above and have a think.... even if its only to reassure me that I'm not going mad :)

like image 317
Jim Anning Avatar asked Apr 15 '11 06:04

Jim Anning


1 Answers

why using onclick="slide()" if u want to slide on click of button then do following

CSS

#box {
       position: absolute;
       width: 120px;
       height: 100px;
       background: #ff0000;
       left: 500px;
}

HTML ( assign some id )

<button id="slide">slide</button>
<div id="box">whetever</div>

jQuery

<script type='text/javascript'>
$(document).ready(function (){
    $('button#slide').click(function(){
            $('#box').animate({'left': 0},3000);
        });
});   
</script>

Working DEMO


UPDATE ( from jQuery1.6)

Smoother Animations

Additionally jQuery is now using the new requestAnimationFrame method provided by browsers to make our animations even smoother. We can use this functionality to avoid calling timers and instead depend upon the browser to provide the best possible animation experience.

.promise()

Just like $.ajax() before it, $.animate() gets “deferred”. jQuery objects can now return a Promise to observe when all animations on a collection have completed:

$(".elements").fadeOut();

$.when( $(".elements") ).done(function( elements ) {
    // all elements faded out
});

HAPPY TO HELP :)

like image 69
diEcho Avatar answered Oct 11 '22 16:10

diEcho