2

I have an issue regarding a parallax scrolling effect I have on the hero cover on a website that I'm working on.

So I want to make the background image on the hero cover scroll at a slower rate than the website as a whole.

Do achieve this I use the following method:

window.requestAnimationFrame = window.requestAnimationFrame
  || window.mozRequestAnimationFrame
  || window.webkitRequestAnimationFrame
  || window.msRequestAnimationFrame
  || function(f){setTimeout(f, 1000/60)}

var hero = document.getElementsByClassName('hero');

function parallax(){
  var scrolltop = window.pageYOffset;
  hero[0].style.backgroundPosition = '25% ' + (+scrolltop * .5 - 217) + 'px';
}

window.addEventListener('scroll', function(){

  requestAnimationFrame(parallax);
  
}, false)
.hero{

 padding: 140px 0px;

 background-image: url("https://s-media-cache-ak0.pinimg.com/originals/0e/18/3b/0e183b91a011639bfed7ebfd6a1f7063.jpg");
 background-repeat: no-repeat;
 background-position: 25% -217px;
 background-size: cover; 
}

.paddingTop{
  padding: 50px 0;
}
.paddingBottom{
  padding: 800px 0;
}
<div class='paddingTop'>
</div>

<div class="hero">
</div>

<div class='paddingBottom'>
</div>

On desktop it's fine, but the trouble starts with tablet and mobile devices. The result on such devices can turn up very choppy and/or the animation entirely lags behind when scrolling the website.

This problem doesn't appear to be consistent with all mobile browsers though.

Here is a little report:

  • Internet on Mobile Android - choppy
  • Firefox on Mobile Android - very choppy
  • Chrome on Mobile Android - perfectly smooth, no issues
  • Firefox on an Android Tablet - the choppiness is less severe than the mobile counterpart
  • Chrome on an Android Tablet - choppy
  • Samsung Internet on an Android Tablet - extremely choppy
  • Safari on iOS - perfectly smooth
Raul Špilev
  • 288
  • 4
  • 18

1 Answers1

3

Parallax scrolling is notoriously tricky in mobile.

Historically, javascript solutions have had issues in mobile because the onscroll event was fired when the page stops scrolling.

You could try this promising CSS-driven solution described in https://developers.google.com/web/updates/2016/12/performant-parallaxing:

The CSS for this approach looks like so:

.container {
  width: 100%;
  height: 100%;
  overflow-x: hidden;
  overflow-y: scroll;
  perspective: 1px;
  perspective-origin: 0 0;
}

.parallax-child {
  transform-origin: 0 0;
  transform: translateZ(-2px) scale(3);
}

Which assumes a snippet of HTML like this:

<div class="container”>
  <div class="parallax-child”></div>
</div>

However, as noted in the link, this technique currently has pitfalls too - particularly in Mobile Safari.

Community
  • 1
  • 1
Mike
  • 3,641
  • 3
  • 29
  • 39