Background position tied to scroll only running once

31 Views Asked by At

I'm trying to tie a background position animation to the mouse scroll, yet it only executes once when scrolling up or down, when what I'd like is for the background position to continue changing as you scroll in both directions. How can I achieve this? Right now it only detects the "first" scroll and then stops.

const el = document.querySelector("#module");

el.addEventListener("wheel", (e) => {
  e.preventDefault();
  el.style.backgroundPositionY = +e.deltaY + "px";
}, { passive: false });

Already tried what is in the pen: https://codepen.io/then00bcoder/pen/vYvQjgX

1

There are 1 best solutions below

0
Rene van den Berg On

You need to add the value of e.deltaY to the existing value instead of just overwriting it:

const el = document.querySelector("#module");

el.addEventListener("wheel", (e) => {
  e.preventDefault();
  let bgPosY = 0;
  if (el.style.backgroundPositionY) bgPosY = parseInt(el.style.backgroundPositionY);
  el.style.backgroundPositionY = bgPosY + e.deltaY + "px";
}, { passive: false });