Fade In/Out Element on Scroll

In this tutorial, you will learn how to fade in and fade out an element on scroll with CSS and JavaScript. Watch the video below for a detailed tutorial.


HTML

<body>
  <div id="filler"></div>

  <div id="container">
    <div id="one"><img src="images/1.jpg"></div>
    <div id="two"><img src="images/2.jpg"></div>
    <div id="three"><img src="images/3.jpg"></div>
  </div>

  <script>
    window.addEventListener('scroll', function() {
      let num = window.scrollY / window.innerHeight;
      let x = 0;

      document.getElementById('filler').style.display = 'none';

      if(num <= 1) {
        document.getElementById('one').style.opacity = 1-num;
        x = (1-num)*2;
        document.getElementById('one').style.transform = 'translate3d('+x+'%,'+x+'%,0px) scale(1,1) rotate(-3deg)';
      } else if(num > 1 && num <= 2) {
        document.getElementById('two').style.opacity = 2-num;
        x = (2-num)*2;
        document.getElementById('two').style.transform = 'translate3d('+x+'%,-'+x+'%,0px) scale(1,1) rotate(5deg)';
      } else if(num > 2 && num <= 3) {
        document.getElementById('three').style.opacity = 3-num;
        x = (3-num)*2;
        document.getElementById('three').style.transform = 'translate3d('+x+'%,'+x+'%,0px) scale(1,1) rotate(-15deg)';
      } else {
        document.getElementById('filler').style.display = 'block';
      }
    })
  </script>
</body>

CSS

body {
  margin: 0;
  background-color: #2e3537;
  height: 3500px;
}

#filler {
  height: 100vh;
  width: 100%;
  display: none;
}

#container {
  position: fixed;
  height: 100vh;
  width: 100%;
}

#container div {
  position: absolute;
  height: 550px;
  width: 380px;
  left: 20%;
  margin-top: 3em;
  border-radius: 25px;
  box-shadow: 0 0 3px black;
}

#container div img {
  height: 100%;
  width: 100%;
  object-fit: cover;
  border-radius: 25px;
}

#one {
  z-index: 3;
  transform: translate3d(0px, 0px, 0px) rotate(-3deg)
}

#two {
  z-index: 2;
  transform: translate3d(-1px, -1px, 0px) rotate(5deg)
}

#three {
  z-index: 1;
  transform: translate3d(0px, 0px, 0px) rotate(-15deg)
}

Image Source

https://unsplash.com/photos/83ypHTv6J2M?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink
https://unsplash.com/photos/ZwKCWVFdrcs?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink
https://unsplash.com/photos/jGibpsPwKOA?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink