Search code examples
javascripthtmlcssparallax

Parallax script gets laggy in chrome and on mobile devices


I use this code for a parallax effect for a website I'm creating, works great in safari and firefox(mac). But in chrome(mac) it gets laggy, the same for when I try it on iPad and on my iPhone 6.

Javascript:

  var ypos,image;
  function parallax() {
    image = document.getElementById('bgImage');
    ypos = window.pageYOffset;
    image.style.top = ypos * .4+ 'px';
}
window.addEventListener('scroll', parallax),false;

html:

    <img class="img-responsive" id="bgImage" src="images/bgtopg.jpg">
</div>
     <div id="box1" class="content">
            <h1>Heading</h1>
            <p>Lorem ipsum dolor sit amet.....</p>      
        </div>

(img-responsive - from bootstrap)

css:

#bgImage {
    position: relative;
    z-index: -1
  }

Any ideas what is causing the lag-effect?


Solution

  • You could try doing the parallax animation effect with translateY instead of manipulating the top style of the image. This is an excellent post by Paul Irish that describes why you should be doing translation instead of top/left/right/bottom.

    So instead of:

    image.style.top = ypos * .4+ 'px';
    

    You could do:

    image.style.webkitTransform = 'translateY(' + ypos * .4 + 'px)';
    image.style.transform = 'translateY(' + ypos * .4 + 'px)';
    

    Good luck, let me know if it helps!