Day13 of #100DaysOfCode

Kushagra Kesav
2 min readFeb 20, 2022

--

#CodeTogether Day 13/100

Hii folks 🙌

Today I have completed the 13th video of JavaScript30!

Project 13: Slide-in on Scroll

Source: https://javascript30.com

Learnings:

Today I got the starter HTML file on a seemingly very long passage of lorem ipsum.

Slide-in-on-Scroll

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

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

Hidden-Image

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:

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

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:

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

window.scrollY + window.innerHeight will give you the exact number (in pixels) of where the bottom of your screen is currently located in relation to where the webpage is scrolled to!!

Today I Learned (T-I-L):

  • Debounce function
  • element.classList.add() & element.classList.remove()✨

That is all for Day13 ✅

Thanks for reading, See you tomorrow!

--

--

Kushagra Kesav
Kushagra Kesav

Written by Kushagra Kesav

Developer Relations | Communities | Software Engineering | https://www.linkedin.com/in/kushagrakesav

No responses yet