Jump to content
Search Community

using gsap.getProperty in foreach

D.Cus test
Moderator Tag

Recommended Posts

For this, is there a specific reason you want to use a fromTo animation? If you just use .to, it works just fine. What's happening is, in your forEach, the entire animation up at once, so all of the initial y values in the from are set to 0. To avoid this you could measure them all and set them via index as you to in the to part of your animation.

  • Like 1
Link to comment
Share on other sites

9 minutes ago, D.Cus said:

@elegantseagulls If .to will work when incorporating scrollTigger as well then that is fine. I just find it very strange that it will console log the value I need but not set in in the animation 

I think you might be misunderstanding what happens at a JS level (this isn't related to GSAP really). You're looping through everything IMMEDIATELY, and reading the "y" value AT THAT TIME (which is 0 in this case). But it looks like mentally, you're thinking of it as though each iteration of the .forEach() is rendering the animation as if it's finished before the next iteration (but it hasn't even started yet). 

 

Another option is to track the value like this: 

var tl = gsap.timeline({ defaults: { duration: 4, ease: Power4.easeInOut}}),
    elements = gsap.utils.toArray('.focus'),
    y = gsap.getProperty("svg", "y");

elements.forEach(function (value, i) {
   const nextY = y - 400 * i;
   tl.addLabel('Start'+i)
    .fromTo('.canvas', 
      {y: y},
      {y: nextY}
      , 'Start'+i)
      
    .addLabel('End'+i)
    .set('.canvas', {y: (-400 * (i+1))}, 'End'+i)
    
    .add(function(){ console.log(gsap.getProperty('svg', 'y'))});
  y = nextY;
});

 

  • Like 4
Link to comment
Share on other sites

Also pay attention to how you increment your nextY value.

 

const nextY = y - 400 * i

 

"y" 0 "nextY" 0 for "i" 0

"y" 0 "nextY" -400 for "i" 1 ==> we are skipping -800 with this expression and jump right to -1200

"y" -400 "nextY" -1200 for "i" 2

"y" -1200 "nextY" -2400 for "i" 3

 

What you probably want instead is

 

const nextY = - i * 400  ;

 

"y" 0 "nextY" 0 for "i" 0

"y" 0 "nextY" -400 for "i" 1

"y" -400 "nextY" -800 for "i" 2

"y" -800 "nextY" -1200 for "i" 3

 

  • 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...