Change Image on Scroll

In this tutorial, you will learn how to change the background image on scroll using CSS and JavaScript. When scrolled up, the previous background images are shown back. Watch the video below for a detailed tutorial.


HTML

<div class="section">
    <div class="image-container">
      <div class="image" style="background-image: url('images/img1.jpg')"></div>
    </div>
  </div>
  <div class="section">
    <div class="image-container">
      <div class="image" style="background-image: url('images/img2.jpg')"></div>
    </div>
  </div>
  <div class="section">
    <div class="image-container">
      <div class="image" style="background-image: url('images/img3.jpg')"></div>
    </div>
  </div>

  <script>
    window.onscroll = function() { changeImage() }

    function changeImage() {
      var scroll = window.scrollY + (window.innerHeight/3);

      [...document.getElementsByClassName('section')].forEach(el => {
        el.classList.remove('active');

        if(el.offsetTop <= scroll && el.offsetTop + el.offsetHeight > scroll) {
          el.classList.add('active');
        }
      })
    } changeImage();
  </script>

CSS

body {
  margin: 0;
}

.section {
  display: flex;
  min-height: 100vh;
  position: relative;
}

.image-container {
  position: relative;
  display: flex;
}

.image {
  height: 100vh;
  position: fixed;
  width: 100%;
  top: 0;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  mix-blend-mode: multiply;
  filter: blur(30px);
  opacity: 0;
  transition: filter 0.5s ease, opacity 0.5s ease;
}

.section.active .image {
  opacity: 1;
  filter: blur(0);
}

Image Source

https://unsplash.com/photos/T7K4aEPoGGk?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink
https://unsplash.com/photos/T7K4aEPoGGk?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink
https://unsplash.com/photos/KMn4VEeEPR8?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink