Parallax Background With Vanilla JS

To create a parallax effect on a CSS background image with vanilla JavaScript, you can listen to the scroll event and update the background-position CSS property of the element containing the background image.

Here’s an example code snippet that demonstrates how to achieve this effect:

<script>
 // Give class name ".parallax" to your section
const parallaxContainer = document.querySelector('.parallax');

// Replace "0.15" with the desired parallax strength (lower values make the effect less pronounced)
const parallaxStrength = 0.15;

window.addEventListener('scroll', () => {
  const scrollPosition = window.pageYOffset;
  const parallaxOffset = scrollPosition * parallaxStrength;
  const backgroundPosition = `50% ${50 - parallaxOffset}%`;

  parallaxContainer.style.backgroundPosition = backgroundPosition;
});

</script>

In this code snippet, we select the element containing the parallax background image using querySelector. We then listen to the scroll event on the window object, calculate the current scroll position using window.pageYOffset, and apply a parallax offset to the background-position CSS property based on the scroll position and the desired parallax strength.

The background-position property is updated on each scroll event, resulting in a smooth parallax effect. Note that the background-image and background-size properties must be set in the CSS for the container element for the parallax effect to work properly.

Adjust the .parallax-container selector and the parallaxStrength value to match your specific needs.

Leave comment or code correction