Search code examples
javascriptparallax

How to make a parallax effect with Vanilla JavaScript ES5?


I'm making a parallax effect with Vanilla JS ES5, but I can't seem to make it work.

Here is codepen: https://codepen.io/Aurelian/pen/XZyjXx?editors=0110

The HTML:

<section class="page-intro">
    <div class="page-intro__img js-parallax" style="background-image: url(https://metrouk2.files.wordpress.com/2017/03/512366437.jpg?w=748&h=498&crop=1);">

    </div>
    <div class="page-intro__overlay"></div>

    <!-- Two Different Parts, big and small -->
    <div class="page-intro__content">
        <h1 class="page-intro__title">Puppy</h1>
        <span class="page-intro__sub-title">Explore how my design process can help your business grow and succeed.</span>
    </div>

    <div class="page-intro__content">

    </div>

</section>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

The JS:

    var parallax = document.getElementsByClassName('js-parallax');
    var xScrollPosition;
  var yScrollPosition;

    function setTranslate(xPos, yPos, el) {
        el.style.transform = "translate3d(" + xPos + ", " + yPos + "px, 0)";
    }

  function scrollLoop() {
      xScrollPosition = window.scrollX;
      yScrollPosition = window.scrollY;

      setTranslate(0, yScrollPosition * -0.2, parallax);

  }
    window.addEventListener("scroll", scrollLoop, false);

Solution

  • It's really good to see more programmers trying vanilla JS.

    You simply have 2 errors. First you need to make sure the document is loaded before trying to access it's content. You wrap everything in this:

    document.addEventListener("DOMContentLoaded", ()=>{
        // content loaded
    });
    

    second

    document.getElementsByClassName('js-parallax');
    

    this does not return an HTML element but an array of elements containing this class. There is only 1 element but it's still an array.

    you can solve it by writing

    document.getElementsByClassName('js-parallax')[0];