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 >
<div ></div>
<div ></div>
<div ></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?
CodePudding user response:
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;
}