0

I want to build a sidescrolling parallax effect with 3 different overlaying pictures that move at different speeds, my code for this is the following:

<div class="parallax-wrapper">
    <div class="parallax1 parallax"></div>
    <div class="parallax2 parallax"></div>
    <div class="parallax3 parallax"></div>
</div>
.parallax-wrapper {
  width: 100%;
  height: 100%;
  background-color: black;
}
.parallax {
  position: fixed;
  display: inline-block;
  width: 500%;
  height: 100%;
  left: 0;
  background-size: auto 100%;
}
.parallax1 {
  background-image: url("../assets/Parallax/Parallax1.svg");
}
.parallax2 {
  background-image: url("../assets/Parallax/Parallax2.svg");
}
.parallax3 {
  background-image: url("../assets/Parallax/Parallax3.svg");
}

and this function that is called on scroll:

function updateScroll(scrollDest){
    parallax1.style.setProperty("left", "-" + (scrollDest * 0.3) + "px")
    parallax2.style.setProperty("left", "-" + (scrollDest * 0.2) + "px")
    parallax3.style.setProperty("left", "-" + (scrollDest * 0.1) + "px")
}

I have done this differently before which worked but had little browser support so I changed it to this method which I thought was very lightweight but sadly it is very laggy on mobile and also not very smooth on my desktop PC, why is this method so slow and how to improve it?

Paul Müller
  • 103
  • 8

1 Answers1

1

I guess you probably just added event listener to window on scroll, that causes calling updateScroll on every scroll event. I'd suggest using throttling and debouncing, to reduce amount of events (Great example you can find on other stack question "Simple throttle in JavaScript".

After reducing the amount of events it'll be a little weird, so I'd suggest adding also transition on left like this:

.parallax {
  transition: left .2s;
}
Adrian Kokot
  • 2,172
  • 2
  • 5
  • 18
  • 1
    I settled on a combination of your answer and the other comment, I used `transform` instead of `left` and also added a `transition: transform .2s` – Paul Müller Jan 03 '22 at 13:01