0

I'm trying to understand how parallax works so that I no longer need to rely on code snippets from others and allow me to build more custom effects so what I did is made a very basic document.

A blue box, an orange square. I placed the circle behind the box, applied a tranform effect, alittle bit of CSS and all seems well. The issue I'm running into is this - shouldn't the thing furthest away from the point of view move slower than what it closer? I've played around with the numbers and cannot figure out why the circle is moving faster that the square...

Can someone explain this to me? Am I misunderstanding something?

<div id="body">
  <div id="box"></div>
  <div id="circle"></div>

#body {
  height: 5000px;
  width: 100%;
  position: relative;
  perspective: 1000px;
  perspective-origin: center;
  transform-style: preserve-3d;
}

#box {
  background: blue;
  width: 400px;
  height: 400px;
  position: absolute;
  top: 400px;
  left: 500px;
  transform:translate3d(0,0,0);
  z-index: -1;
}

#circle {
  background: orange;
  width: 200px;
  height: 200px;
  border-radius: 1000px;
  position: absolute;
  top: 650px;
  left: 350px;
  transform: translate3d(0,0,-2px) scale(1);
  z-index: 1;
}




 window.addEventListener('scroll', function(e) {
  var scrolled = window.pageYOffset;
  var box = document.querySelector('#box');
  var circle = document.querySelector('#circle');

  box.style.transform = `translate3d(0,${(0 + (scrolled * .75))}px, 0)`;
  circle.style.transform = `translate3d(0,${(0 + (-scrolled * .15))}px, -2px) scale(1)`;
});

Link to my test file

Thanks!

Ctsa3
  • 123
  • 1
  • 1
  • 7
  • See this: https://stackoverflow.com/questions/20851452/z-index-is-canceled-by-setting-transformrotate – Dai Oct 01 '19 at 00:44
  • Also, use a passive scroll event-listener to make it less jerky when scrolling. – Dai Oct 01 '19 at 00:45

1 Answers1

0

The translate3d( 0, 0, -2px ) transform on the #circle means it will always be behind #square even when #circle's z-index is higher.

Change it to translate2d (and remove the tz argument) or change it to translate3d( 0, 0, 0 ). The same applies to the scroll event listener.

That said, you don't need any scroll event listener. See this example: it does parallax scrolling without using any scripts: https://codepen.io/tribex/pen/mWNWdz

Dai
  • 141,631
  • 28
  • 261
  • 374