I am trying to recreate a parallax effect site using JavaScript. This means that I have two or more layers that move at different speeds while scrolling.
In my case, I only move one layer, the other remains static: layer 1 = website text; layer 2 = element background;
I use simple source code (with jQuery 1.6.4) for this:
var docwindow = $(window); function newpos(pos, adjust, ratio){ return ((pos - adjust) * ratio) + "px"; } function move(){ var pos = docwindow.scrollTop(); element.css({'top' : newpos(pos, 0, 0.5)}); } $(window).scroll(function(){ move(); });
Problem: - All calculations are performed correctly, and the effect "works" as expected. But in some browsers there are some performance failures (Chrome MAC / Windows, Opera MAC, IE, paradoxically no Safari).
What do I see while scrolling? - Scrolling the background moves in one direction along with the scroll, but sometimes it seems that it jumps several pixels back and then forward several times, which creates a very alarming effect (and not liquid).
The solutions I tried: - adding a timer to limit scroll events - using the .animate () method with a short duration instead of the .css () method.
I also noticed that the animation is smooth when using the .scrollTo method (scrollTo jQuery plugin). Therefore, I suspect that something is wrong with the firing scroll events (too fast).
Have you observed the same behavior? Do you know how to fix this? Can you post a better solution?
Thanks for all the answers.
EDIT # 1: Here you can find the jsfiddle demo (with timer): http://jsfiddle.net/4h9Ye/1/