Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating changing a CSS value with pure JS

Tags:

javascript

Ok so I'm changing the value of the CSS 'left' property, like so:

s_list.style.left = left - amount + 'px';

s_list is a variable which is a UL element. This line gets executed on click of a button. But the effect is instant, to fast to see any sort of animation left. Is there anything i can do with pure JS to slow this down or add a configurable delay to the change?

To see my working demo:

http://jsfiddle.net/benhowdle89/RCkPq/

And possibly suggest a solution!

like image 617
benhowdle89 Avatar asked Mar 11 '26 01:03

benhowdle89


1 Answers

For basic animation, you can use setTimeout or setInterval. However, in modern browsers they are outdated. A more efficient way to animate things around is by using requestAnimationFrame.

function animate(things){
    //Do stuff here.
    requestAnimationFrame(animate);
}

You might ask, "How is this different?" Well, requestAnimationFrame will only redraw the screen only when the user can actually see the element. If the user is on another tab, or scrolled down the page, it won't redraw it. It saves memories in the computer.

Unfortunately, until now every browser still need a prefix. Here's a fix:

if ( !window.requestAnimationFrame ) {
    window.requestAnimationFrame = ( function() {
        return window.webkitRequestAnimationFrame ||  //webkit
        window.mozRequestAnimationFrame ||            //mozilla
        window.oRequestAnimationFrame ||              //opera
        window.msRequestAnimationFrame ||             //IE!
        function(callback, element) {
            window.setTimeout( callback, 1000 / 60 ); //not supported
        };
    } )();
}

UPDATED

LIVE DEMOS:

  1. http://jsfiddle.net/DerekL/4wLsC/
  2. http://jsfiddle.net/DerekL/4wLsC/4/ - Cycle through images (Still no jQuery!)
like image 131
Derek 朕會功夫 Avatar answered Mar 12 '26 15:03

Derek 朕會功夫



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!