How to solve flicker element when scrolling with parallax effect in JavaScript?

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/

+6
source share
1 answer

I think you should use scrollTop () instead and change the starting position to fixed. The problem is that setting it to absolute will cause it to move by default when scrolling up or down.

A flicker occurs because the position is updated as part of the default browser scroll and updated again as part of your script. This will do both positions instead of what you want. With a fixed background, it will never move unless you say so.

I created a demo for you at http://jsfiddle.net/4h9Ye/2/ .

+9
source

Source: https://habr.com/ru/post/906884/


All Articles