javascripthtmlcssparallaxjitter

Webpage parallax background jitters when scrolling


I coded my first website and I wanted a parallax effect on my background when scrolling. It works, but on some computers &/or on some browsers &/or on some window sizes, the background jitters up and down when scrolling, while still sort of maintaining the parallax effect. I cannot figure out exactly what combination leads to the issue, it seems inconsistent.

In css I have a vertically repeating background image on the body of my page (the hexagon pattern):

body {
   background: #fff9ed;
   background-image: url("hexagon-side.png"), url("hexagon-side.png");
   background-position: 0px 0px, 100% 0px;
   background-repeat: repeat-y, repeat-y;
}

Then I used the following javascript that creates the parallax effect, making the hexagons move slower than other elements when you scroll:

window.addEventListener('scroll', function() {
   let scrollTop =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
   var currentOffset = '0px ' + scrollTop / 1.2 + 'px, 100% ' + scrollTop / 1.2 + 'px';
   document.getElementById("parallax").style.backgroundPosition = currentOffset;
});

Finally my body in the html file has the id parallax: <body id="parallax">

Is there a way to fix this issue? Is there a better way to achieve this same effect? What might be causing this?


Solution

  • Adding

    background-attachment: fixed;
    

    to the css body, and changing the currentOffset to be

    var currentOffset = '0px ' + scrollTop / -3 + 'px, 100% ' + scrollTop / -3 + 'px';
    

    Fixed the jittering issues.