Jump to content
Search Community

Using timeline progress() from a class method

Black Ducas test
Moderator Tag

Recommended Posts

Hi, here is the code I'm using to control a timeline via the scroll event:

 

import { gsap } from "gsap"

export default class HorizontalScroll {

  constructor(elClass) {

    // ..... code

    // The animation to use
    this.tl = gsap.timeline({
      paused: true
    })
      .to(this.container, {x: -(this.width - innerWidth), ease: "none"})
    
    // Listen to the scroll event
    this.update();
    this.bindEvents();
  }


  bindEvents() {
    document.addEventListener('scroll', (e) => { this.onScroll(e) });
  }


  /* Handlers
  --------------------------------------------------------- */

  onScroll(e) {
    // Prevent the update from happening too often (throttle the scroll event)
    if (!this.requestId) {
      this.requestId = requestAnimationFrame(this.update);
    }
  }


  /* Actions
  --------------------------------------------------------- */

  update() {
    console.log("update")

    // Update our animation
    this.tl.progress((scrollY - this.startY) / this.finishDistance); //<== this causes error

    // Let the scroll event fire again
    this.requestId = null;
  }

}

but I get this error

Uncaught TypeError: Cannot read property 'tl' of undefined

caused by this line inside update() method

this.tl.progress((scrollY - this.startY) / this.finishDistance);

 

Don't get where I'm wrong?

Link to comment
Share on other sites

It's a scope issue from your requestAnimationFrame calls.

 

Take your pick. I like using class fields for events.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields

 


// function as class field
class MyClass {
   
  update = () => {
    console.log(this.foo);
  }
  
  constructor() {
    this.foo = "FOO"
    
    requestAnimationFrame(this.update)
  }
}

// function inside constructor
class MyClass {
  
  constructor() {
    this.foo = "FOO"
    
    this.update = () => {
      console.log(this.foo);
    }
    
    requestAnimationFrame(this.update);
  }
}

// use a function to call it
class MyClass {
  
  constructor() {
    this.foo = "FOO"
    
    requestAnimationFrame(() => this.update())
  }
  
  update() {
    console.log(this.foo);
  }
}

 

 

 

 

  • Like 4
  • Thanks 1
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...