Search code examples
jqueryparallax

How do I adjust item in Parallax?


I'd like to move a div or section with js. I have a code for this that is running in Chrome. This code positions the items in accordance with display. My problem is that this code is not that logical and isn't so good on Android and other devices.

So please check my code, and help me rewrite so that the items are in accordance with other items not the the display.

$(window).bind('scroll',function(e){
    parallaxScroll();
});

function parallaxScroll(){
    var scrolled = $(document).scrollTop();
    if (scrolled < 2000) {
    $('#land1').css('top',(0-(scrolled*.39))+'px');
    $('#trees1').css('top',(0-(scrolled*.4))+'px');
    } else {
        ertek = -500;
    $('#trees1').css('top',ertek+'px');
    $('#land1').css('top',ertek+'px');
    }
}

Solution

  • Actually, simply using the scroll event is a bad choice (but a common one unfortunately).

    The scroll event is triggered a lot when a user scrolls through the page. It sometimes is triggered too much, and other times not as much as you'd want. What I mean is that the scroll event is not consistent with the "frame refresh rate" of your browser. I can be triggered twice for a frame (making the animation faster, as the browser will squeeze two steps in one), or not at all for an other (making the animation slower). So the animation doesn't seem fluid, especially on less powerful devices.

    You have basically two solutions :

    The requestAnimationFrame solution

    Example : http://codepen.io/foleyatwork/pen/xButc/

    Technically, it doesn't require too much change from your original code (meaning you can keep all your ratios that you found, etc). You "just" ask to your browser to wait until the next frame refresh to update the position of the given elements. The animation appears smooth, even if you're triggering scroll events as much as before.

    More info here : http://www.html5rocks.com/en/tutorials/speed/animations/

    The CSS with "transform" solution

    Example : http://codepen.io/keithclark/pen/JycFw

    This one requires to trash everything you've done in javascript, to go to a full CSS3 animation, using the perspective and transform elements. It has two big advantages :

    • Your layers are organized spatially and logically : you tell how far is a layer by how much from a common origin. No more "I have to multiply its position by 0.39 to make it seem like it is in the background - oh wait, was it 0.39 or 0.24 ?".
    • Most browsers now have hardware accelerated CSS animation. So you don't even need to manage the position for each element at each frame, you let the GPU of the device do it for you (and it's surely a lot faster than you).

    HTML5Rocks actually has a good post on parallax here. Be advised that it was written two years ago, so some limitations described may not be present now. But it gives a few alternatives, so you can choose the best for your case.