Search code examples
javascriptparallax

Smooth parallax effect


I'm trying to make a parallax-effect. Yes, I understand that there are ready-made solutions, but for the purpose of self-education I've decided to write this from scratch and with "plain" js (without jq). So I faced with the problem that the "layers" that I process via the js, shaking, and it appears only when I scroll page with a mousewheel. The manual scrolling using scrollbar works fine. I use this code for a layer update:

window.onscroll = function () {
    requestAnimFrame(scrollCalc);
}

scrollCalc = function() {
    for (var i = 0; i < parallaxes.length; i++) {
        var offset = (parallaxParents[i].getBoundingClientRect().top) * (-1) * parallaxes[i].magnitude;
        parallaxes[i].style.transform = "translate3d(0, " + offset + "px, 0)";
    }
}

requestAnimFrame = (
    window.requestAnimationFrame       ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame    ||
    window.oRequestAnimationFrame      ||
    window.msRequestAnimationFrame     ||
    function(callback) {
        setTimeout(callback, 1000 / 60);
    }
);

parallaxParents variable stores parent dom elements of parallax layers, and parallaxes variable storese parallax layers itself.

PS: those shakes I saw on chrome, firefox has microlags. I believe that the root cause of these two nuances can be covered in the same issue.

And sorry for my bad english


Solution

  • Already solved. I've overrided default mousewheel function in this way.

        window.onmousewheel = function (e) {
            e.preventDefault();
            window.scrollTo(window.pageXOffset + e.deltaX/scrollRatio, window.pageYOffset + e.deltaY/scrollRatio)
        }
    

    Maybe it's not the best solution, but it works fine. Shakes on scroll disappeared.