Parallax Image With Vanilla JS

This code snippet will give you cool parallax image effect on page scroll. Wrap image with div and give “.parallax” class to div. Adjust parallaxFactor value to change parallax speed.

CSS:

.parallax {
  position: relative;
  overflow: hidden;
}

.parallax image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: auto;
  transform: translateZ(0);
}

JS:

<script>
  let parallaxFactor = 50; // Set the default parallax factor

  window.addEventListener('scroll', function() {
    const parallaxElements = document.querySelectorAll('.parallax');

    for (let i = 0; i < parallaxElements.length; i++) {
      const elementTop = parallaxElements[i].getBoundingClientRect().top;
      const elementHeight = parallaxElements[i].offsetHeight;
      const scrollPosition = window.pageYOffset;
      const parallaxAmount = elementTop - scrollPosition;
      const parallaxOffset = (parallaxAmount / elementHeight) * parallaxFactor; // Use the parallaxFactor variable
      
      parallaxElements[i].style.transform = 'translateY(' + parallaxOffset + '%)';
    }
  });
</script>

If you want parallax to go opposite direction, use this JS below. Your parallax image will go to button of the page when you scroll.

JS for opposite direction :

<script>
  let parallaxFactor = 50; // Set the default parallax factor
  window.addEventListener('scroll', function() {
    const parallaxElements = document.querySelectorAll('.parallax');
    const windowHeight = window.innerHeight;
    const documentHeight = document.documentElement.scrollHeight;

    for (let i = 0; i < parallaxElements.length; i++) {
      const elementTop = parallaxElements[i].getBoundingClientRect().top;
      const elementHeight = parallaxElements[i].offsetHeight;
      const scrollPosition = window.pageYOffset;

      const parallaxAmount = (documentHeight - windowHeight) - scrollPosition - (elementTop - scrollPosition);
      const parallaxOffset = (parallaxAmount / elementHeight) * parallaxFactor;

      parallaxElements[i].style.transform = 'translateY(' + parallaxOffset + '%)';
    }
  });
</script>

Leave comment or code correction