1

I am trying to create a parallax effect on the scroll. "Po Ta To" have to scroll at different speeds. however it isn't working.

window.addEventListener("scroll", function(e) {

  const target = document.querySelectorAll('.parallax');
  var index = 0,
    length = target.length;

  for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.speed;
    target[index].style.transform = 'translate3d(0px, ' + pos + 'px, 0px)';
  }
});
* {
  margin: 0px;
  padding: 0px;
  width: 100%;
  font-family: Montserrat;
  height: 200vh;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

ul {
  height: 30vh;
  text-align: center;
  white-space: nowrap;
}

li {
  font-size: 100px;
  font-weight: bold;
  text-align: center;
  display: inline;
}
<section>
  <ul>
    <li class="parallax" data-speed="2">PO</li>
    <li class="parallax" data-speed="1.5">TA</li>
    <li class="parallax" data-speed="2.3">TO</li>
  </ul>
</section>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
killerprince182
  • 455
  • 2
  • 12
  • 1
    Possible duplicate of [CSS transform doesn't work on inline elements](https://stackoverflow.com/questions/14883250/css-transform-doesnt-work-on-inline-elements) Short answer, it doesn't work because the `li` aren't a `display: block` – George Oct 14 '19 at 14:38
  • Here is a working example on your code: https://codepen.io/hac/pen/JjjXKPO – Andrei Oct 14 '19 at 14:59

1 Answers1

1

The transform isn't working properly on your li elements because they are inline. They need to be some kind of block to work properly.

See here with inline-block. I've obviously had to set a width on them to stop them taking up the full width of the page:

window.addEventListener("scroll", function(e) {
  const target = document.querySelectorAll('.parallax');
  var index = 0,
    length = target.length;

  for (index; index < length; index++) {
    var pos = window.pageYOffset * target[index].dataset.speed;
    target[index].style.transform = 'translateY(' + pos + 'px)';
  }
});
* {
  margin: 0px;
  padding: 0px;
  width: 100%;
  font-family: Montserrat;
  height: 200vh;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

ul {
  height: 30vh;
  text-align: center;
  white-space: nowrap;
}

li {
  font-size: 100px;
  font-weight: bold;
  text-align: center;
  display: inline-block;
  width: 130px;
}
<section>
  <ul>
    <li class="parallax" data-speed="2">PO</li>
    <li class="parallax" data-speed="1.5">TA</li>
    <li class="parallax" data-speed="2.3">TO</li>
  </ul>
</section>

Tweak as necessary to achieve the desired effect.

Martin
  • 16,093
  • 1
  • 29
  • 48