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!
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With