JavaScript-30-Day-13
Tags: javascript, css, github, webdev
Published: 2021-06-13 16:02:35

#<center>Slide in on Scroll</center>

**[demo](https://cenacrharsh.github.io/JS-30-DAY-13/)**

![ss.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgyjfe2arssxufrzj282.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.

```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);
      }

```

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.

```css
 .slide-in.active {
        opacity: 1;
        transform: translateX(0%) scale(1);
      }
```

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:

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

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

```javascript
const sliderImages = document.querySelectorAll(".slide-in");
```

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.

```javascript
window.addEventListener("scroll", debounce(checkSlide));
```

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)`.

```javascript
function checkSlide(e) {
console.count(e);
}
```

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.

```javascript
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);
        };
      }
```

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

```javascript
const slideInAt =
            window.scrollY + window.innerHeight - sliderImage.height / 2;
```

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

```javascript
const imageBottom = sliderImage.offsetTop + sliderImage.height;
```

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:
```javascript
const isHalfShown = slideInAt > sliderImage.offsetTop;
```

Secondly if we have not scrolled past the image:
```javascript
const isNotScrolledPast = window.scrollY < imageBottom;
```

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

```javascript
if (isHalfShown && isNotScrolledPast) {
            sliderImage.classList.add("active");
          } else {
            sliderImage.classList.remove("active");
          }
```

Here is the complete JavaScript code:

```javascript
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));
```
and with this our project for the day was completed.

GitHub repo:
{% github cenacrharsh/JS-30-DAY-13 no-readme %}

###Blog on Day-12 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-12-2k45 %}

###Blog on Day-11 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-11-1icc %}

###Blog on Day-10 of javascript30
{% link https://dev.to/cenacr007_harsh/javascript-30-day-10-2nl5 %}

[Follow me on Twitter](https://twitter.com/cenacr007_harsh)
[Follow me on Linkedin](https://www.linkedin.com/in/kumarharsh22/)

**DEV Profile**

{% user cenacr007_harsh %}

You can also do the challenge at [javascript30](https://javascript30.com/)

Thanks @wesbos  , [WesBos](https://github.com/wesbos) to share this with us! 😊💖

**Please comment and let me know your views**
##Thank You!