All Articles

Javascript Slide in on Scroll Animation

This is day 13 in my #javascript30 journey. This is the free course from Wes Bos that lets you brush up on your JavaScript skills via 30 projects.

Yesterday we created our very own Easter Egg using Key Sequence Detection. You can keep track of all the projects we’re building here.

Today we’re exploring Slide in on Scroll.

Today I open the starter HTML file on a seemingly never ending passage of lorem ipsum.

Lorem Ipsum

The aim of today is to animate images to appear (via a slide transition) as we scroll down the page.

Wes notes that he doesn’t actually like the effect that this animation gives to the website (and I’m tempted to agree with him). The over animation makes it look dated. But he concedes that there are a lot of window events that we can practice from this exercise.

So let’s get into it.

When to Animate the Images

By default all of the images on the page are hidden:

Hidden Images

This is achieved by the default styling applied to the images:

.slide-in { opacity:0; transition:all .5s; }
.align-left.slide-in { transform:translateX(-30%) scale(0.95); } .align-right.slide-in { transform:translateX(30%) scale(0.95); }

The style that we want to apply to the images when they’re to be slid in is: { opacity:1; transform:translateX(0%) scale(1); }

To do this we need to:

  • Select all the images.
  • Listen for the scroll event on the window.
  • Create a timeout function that caps the number of scroll events we can listen for in a specific time-period. We are setting this time out for once every 20 milliseconds.
  • Create a function the checks whether an image needs to slide in at this window location.

For each image, we need to determine at what scroll locations should the image be visible.

To do this we are going to set some rules:

  • The image should slide in when 50% of the image height is visible.
  • The image should slide out when it is out of view.

When this all comes together we have:

const sliderImages = document.querySelectorAll(‘.slide-in’)
function checkSlide(e) { sliderImages.forEach(sliderImage => { //halfway through the image const slideInAt = (window.scrollY + window.innerHeight) - sliderImage.height / 2 //bottom of the image const imageBottom = sliderImage.offsetTop + sliderImage.height //is it shown? const isHalfShown = slideInAt > sliderImage.offsetTop const isNotScrolledPast = window.scrollY < imageBottom if(isHalfShown && isNotScrolledPast) { sliderImage.classList.add(‘active’) } else { sliderImage.classList.remove(‘active’) }
}) }
window.addEventListener(‘scroll’, debounce(checkSlide))

Not Shown - debounce function

This looks like this:

Images slide in on scroll

Now that everything has been done I have pushed this project live to a Firebase project. You can view it live here.

You can keep track of all the projects in this JavaScript30 challenge here.