Jump to content
Search Community

ScrollTrigger, ToggleClass and Targets

Jamesh test
Moderator Tag

Recommended Posts

Loving ScrollTrigger. I've got the functionality of what I want to do working, codepen URL . However, I am using IDs to trigger and another ID to toggleClass by using toggleClass: { targets: timelineImage, className: 'active' },. I have a lot of images, 38, and I'm sure there is a better way in which to target the elements rather than having to specifically generate code each time for each image and section and therefore generating essentially repetitive code, as well as making making it more dynamic for future use. 

 

I started working along the lines of: 

 

if (document.querySelector('.timeline')) {
const timelineContainers = document.querySelectorAll('.timeline-content');
 
timelineContainers.forEach((container) => {
const timelineTrigger = container.querySelectorAll('.timeline-trigger');
const timelineImage = document.querySelectorAll('.timeline-image');
ScrollTrigger.create({
trigger: timelineTrigger,
markers: true,
toggleClass: { targets: timelineImage, className: 'active' },
start: 'top 40%',
 
});
});
}

 

but this obviously adds the className to all the .timeline-images and not one-by-one as you scroll past each .timeline-content, hence my workings thus far.

 

Thanks in advance!

 

PS.  Is it best practice not to animate the same element as your ScrollTrigger? 

 

 

See the Pen YzwzdpP by jame5 (@jame5) on CodePen

Link to comment
Share on other sites

Hey Jamesh.  Since your images and sections have the same number, you can make use of that to select the appropriate section:

See the Pen GRoRzvx?editors=0010 by GreenSock (@GreenSock) on CodePen

 

If that's not true in your production site, there are other ways of pointing to the correct section. For example I make use of data attributes when I did the same sort of thing in this pen (I have more complex animations going on in this one):

See the Pen YzyqVNe by GreenSock (@GreenSock) on CodePen

  • Like 3
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...