Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript using requestAnimationFrame on scroll event

I have a problem when using window.requestAnimationFrame on a scroll event.

I want to move a DIV using CSS transform:translate3D.

document.getElementById("content").addEventListener("scroll", function(){

var getScroll = this.scrollTop * 1.2;

function repeatOften() {

    document.getElementById("moveable").style.transform = 
        "translate3D(0," + getScroll + "px, 0)";
    requestAnimationFrame(repeatOften);

}

requestAnimationFrame(repeatOften); 

});

Here's a fiddle: https://jsfiddle.net/tcayv8dp/

Why is this animation not running smoothly? What is wrong with my code?

Thank you!

like image 528
Ching Ching Avatar asked Mar 15 '16 17:03

Ching Ching


1 Answers

The animation seems smooth to me.

However, you shouldn't be calling requestAnimationFrame inside the function as those calls will keep running endlessly.

This is how I would improve your code:

// define the function outside the onscroll function so it doesn't get redefined
var getScroll;
function repeatOften() {
    // use translateY instead of translate3D
    document.getElementById("moveable").style.transform = "translateY(" + getScroll + "px)";
};

document.getElementById("content").addEventListener("scroll", function(){

    getScroll = this.scrollTop * 1.2;
    requestAnimationFrame(repeatOften);

});
like image 176
pishpish Avatar answered Nov 15 '22 05:11

pishpish