DEV Community

loading...
Cover image for JavaScript-30-Day-13

JavaScript-30-Day-13

KUMAR HARSH
The best way to learn is to teach. Programmer by Passion and Developer for Fun, and I love sharing my journey with everyone.
Updated on ・4 min read

Slide in on Scroll

demo

ss.png

On Day-13 of JS-30 we made a Slide-in-on-Scroll, that is when you slide down, the image sort of slide themselves in form left or right. The images are hidden by default using CSS.

.slide-in {
        opacity: 0;
        transition: all 0.5s;
      }

      .align-left.slide-in {
        transform: translateX(-30%) scale(0.95);
      }

      .align-right.slide-in {
        transform: translateX(30%) scale(0.95);
      }

Enter fullscreen mode Exit fullscreen mode

Basically we have made their opacity to be 0 and using translate slightly pushed them off the window. We also do scale of 0.95 to get a fade-in effect.

During sliding in we add a active class to it which will make their opacity 1 and scale them back to normal size.

 .slide-in.active {
        opacity: 1;
        transform: translateX(0%) scale(1);
      }
Enter fullscreen mode Exit fullscreen mode

So let's get right into the JavaScript.

First thing we need to do is select all the images that we are going to be listening for by using slide-in class which we gave to all our images, for example:

      <img src="http://unsplash.it/400/400" class="align-left slide-in" />

<img src="http://unsplash.it/400/400" class="align-right slide-in" />
Enter fullscreen mode Exit fullscreen mode
const sliderImages = document.querySelectorAll(".slide-in");
Enter fullscreen mode Exit fullscreen mode

Now we'll create a function called checkSlide() that will run every time the person scrolls, so we'll add an eventListener for the scroll event.

window.addEventListener("scroll", debounce(checkSlide));
Enter fullscreen mode Exit fullscreen mode

Now you might be wondering what is this debounce thing we have wrapped around the checkSlide function.

Essentially the scroll event gets fired off hundreds of times in one scroll and this can cause a little bit of a performance issue.
We can check how many times the event gets fired off by using console.count(e).

function checkSlide(e) {
console.count(e);
}
Enter fullscreen mode Exit fullscreen mode

So to avoid this performance issue we use a debouncer function. What this function essentially does is that whatever function is supplied to it and whatever wait interval is set in it, it makes sure that the passed function is run once every x seconds, where x is the wait interval in millisecond.

function debounce(func, wait = 20, immediate = true) {
        var timeout;
        return function () {
          var context = this,
            args = arguments;
          var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
      }
Enter fullscreen mode Exit fullscreen mode

Here func is the checkSlide function we have passed here debounce(checkSlide) and wait is 20 millisecond. So the debouncer function runs every time but the checkSlide function runs once every 20ms now, which can be verified using the console.count.

Note: It's always a good idea to decbounce scroll event.

Now inside the checkSlide function we'll do the math for when the Images should slide in and when should they slide out.

First of all we'll loop every single image and figure out when each image need to be shown.

What we want is while scrolling when we reach half of the image height on our window the image should slide-in and when we have scrolled past the bottom of the image we'll slide it out, so that we can have the same slide in effect when we scroll back up.

This calculates the distance in pixel of the image half way through

const slideInAt =
            window.scrollY + window.innerHeight - sliderImage.height / 2;
Enter fullscreen mode Exit fullscreen mode

Here window.scrollY gives how far we have scrolled down from the top of the browser window, but it gives the distance only upto the the top of the viewport and we want to know the distance upto the bottom of our window so we add window.innerHeight to it. Now since we want the animation to happen when we are exactly halfway through the image so we subtract that much distance using (sliderImage.height / 2).

Now slideInAt contains the exact pixel when the image should slide in.

Similarly we calculate when we reach the bottom of the image by using

const imageBottom = sliderImage.offsetTop + sliderImage.height;
Enter fullscreen mode Exit fullscreen mode

Where sliderImage.offsetTop gives the distance in pixel between the top of he image and the top of the browser window and hence by adding sliderImage.height we get the bottom of the image.

Now we need to determine 2 things:

First is the image half shown which we do by:

const isHalfShown = slideInAt > sliderImage.offsetTop;
Enter fullscreen mode Exit fullscreen mode

Secondly if we have not scrolled past the image:

const isNotScrolledPast = window.scrollY < imageBottom;
Enter fullscreen mode Exit fullscreen mode

and only if both of them are true we add the active class to the slider images else we remove it.

if (isHalfShown && isNotScrolledPast) {
            sliderImage.classList.add("active");
          } else {
            sliderImage.classList.remove("active");
          }
Enter fullscreen mode Exit fullscreen mode

Here is the complete JavaScript code:

function debounce(func, wait = 20, immediate = true) {
        var timeout;
        return function () {
          var context = this,
            args = arguments;
          var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
          };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
      }

      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 iamge
          const imageBottom = sliderImage.offsetTop + sliderImage.height;

          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));
Enter fullscreen mode Exit fullscreen mode

and with this our project for the day was completed.

GitHub repo:

Blog on Day-12 of javascript30

Blog on Day-11 of javascript30

Blog on Day-10 of javascript30

Follow me on Twitter
Follow me on Linkedin

DEV Profile

cenacr007_harsh image

You can also do the challenge at javascript30

Thanks @wesbos , WesBos to share this with us! 😊💖

Please comment and let me know your views

Thank You!

Discussion (7)

Collapse
rohitk570 profile image
ROHIT KUMAR

WOW seems cool

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

thanks

Collapse
mickaelchanrion profile image
Mickael Chanrion

Why not use the IntersectionObserver API?

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

Actually there are a ton of ways to achieve the same results this is just how Wes Bos did it his tutorial. His tutorial mainly focusses on doing the projects using Vanilla JS.

Collapse
kritebh profile image
Kritebh Lagan Bibhakar

It feels like Lazy Load 👍

Collapse
rash123 profile image
RASHMI VERMA

Best

Collapse
cenacr007_harsh profile image
KUMAR HARSH Author

thanks