Hey everyone,
I recently asked a question to which @ZachSaucier gave an awesome response and helped me discover Intersection Observer.
Now I am trying to work a piece of code using Intersection Observer to create a parallax gallery.
Here is a basic CodePen example
I started targeting the .scrolled-element:nth-of-type(2n) which works well to target every second instance of .scrolled-element
Here is my code:
// Setup Intersection Observer and GSAP homepage
const observerElements = document.querySelectorAll('.trigger-element');
const observerOptions = {
root: null,
rootMargin: '0px 0px',
threshold: 0
};
observerElements.forEach(el => {
const scrolled = el.querySelectorAll('.scrolled-element:nth-of-type(2n)');
el.tl = gsap.timeline({paused: true});
el.tl
.to(scrolled, {y: -200, ease: 'power2.inOut'})
el.observer = new IntersectionObserver(entry => {
if (entry[0].intersectionRatio > 0) {
gsap.ticker.add(el.progressTween)
} else {
gsap.ticker.remove(el.progressTween)
}
}, observerOptions);
el.progressTween = () => {
// Get scroll distance to bottom of viewport.
const scrollPosition = (window.scrollY + window.innerHeight);
// Get element's position relative to bottom of viewport.
const elPosition = (scrollPosition - el.offsetTop);
// Set desired duration.
const durationDistance = (window.innerHeight + el.offsetHeight);
// Calculate tween progresss.
const currentProgress = (elPosition / durationDistance);
// Set progress of gsap timeline.
el.tl.progress(currentProgress);
}
el.observer.observe(el);
});
I then wanted to start targeting more of the same selector so added them like so:
const scrolled1 = el.querySelectorAll('.scrolled-element:nth-of-type(1n)');
const scrolled2 = el.querySelectorAll('.scrolled-element:nth-of-type(2n)');
const scrolled3 = el.querySelectorAll('.scrolled-element:nth-of-type(3n)');
const scrolled4 = el.querySelectorAll('.scrolled-element:nth-of-type(4n)');
el.tl = gsap.timeline({paused: true});
el.tl
.to(scrolled1, {y: -150, ease: 'power2.inOut'})
.to(scrolled2, {y: -100, ease: 'power2.inOut'})
.to(scrolled3, {y: -200, ease: 'power2.inOut'})
.to(scrolled4, {y: -250, ease: 'power2.inOut'})
The reason I need the nth-of-type is because this ties in to a piece of code where my client can repeat content, therefore repeating the same bits of code and using the same classes over and over again to build a gallery of content/images. I'd like to set it up so that I can define every 2nd, 3rd, 4th etc item to move a specific amount with different Y values.
Except using the above code, it bugs out and sometimes won't animate past the first element, so I'm wondering if this is the best way to even add multiples of selectors?
If using nth-of-type isn't the best path to go down, I am all ears to other ideas too
Many thanks in advance for any assistance!