Slide in on scroll

Using js to find out when images are reached when scrolling down the page. From here you can add and remove classes that cause images to have transition and styles of your choice.

First we need to select all classes we want the function to be called on. Using querySelectorAll allows you to use the forEach method as the classes are stored in an array.

Find the position of the scroll by using 'window.scrollY'. Find the height of the viewport by using 'window.innerHeight'

Combining these with the image height, we can work out when half the image is visible.

       const slideInAt = (window.scrollY + window.innerHeight) - sliderImage.height / 2;

From here we can work out where the bottom of the image is.

       const imageBottom = sliderImage.offsetTop + sliderImage.height;

And half way through the image

       const isHalfShown = slideInAt > sliderImage.offsetTop;

And if the user has not scrolled past the image.

      const isNoScrolledPast = window.scrollY < imageBottom;

Gathering this information, we can combine these into if and else.

     if(isHalfShown && isNoScrolledPast) {
      sliderImage.classList.add('active');
   } else {
      sliderImage.classList.remove('active');
   }
  })

With the above code stored into a function, we can add the event listener 'scroll'.

    window.addEventListener('scroll', debounce(checkSlide));

Debounce function is added as well to prevent the browser from calling the function multiple times causes a crash, or slower speeds when not needed. Here's more information on debounce

Things learnt

  1. Debounce
  2. window scroll positions
  3. scroll method
  4. finding positions of DOM elements
  5. Translate active class

Completed project

See the Pen slide on scroll by Harry Beckwith (@fun) on CodePen.


1,992 0 32