Jump to content
Search Community

this.x is undefined but works anyway with gsap.to for some elements, but not others?

Lawston test
Moderator Tag

Recommended Posts

In the attached pen, the text draggable can be restored to its original center position using the 'restore' button, despite the 'this.x' variable used to compute that position is declared 'undefined' when printed to the console. Using the same 'this.x' variable to similarly restore the green line element to its starting position does not move, or flies off the SVG boundary. 

Thoughts?

 

See the Pen GRrEjvz by Lawston (@Lawston) on CodePen

Link to comment
Share on other sites

If you console.log(this) when you click the restore button, you'll see that is the window. You have a global endX variable so you get a value returned. There is no "x' variable so you get undefined.

 

I'd think the easiest solution would be to set the x1/x2 attributes upon clicking restore like this.

  gsap.to(objLineDivider, {
    attr: {
      x1: originalX,
      x2: originalX
    }
  });

Make sense?

 

Happy tweening.

:)

 

  • Like 2
Link to comment
Share on other sites

1 hour ago, Lawston said:

despite the 'this.x' variable used to compute that position is declared 'undefined' when printed to the console

 

this is the scope of the button when you press it. If you want the function to have to the scope of your draggable, you would have to use call or apply like so.

 

var draggable = new Draggable(objTextHandle, {
  bounds: "#rectBA",
  onDrag: function () {
    objLineDivider.setAttribute("x1", this.x + originalX);
    objLineDivider.setAttribute("x2", this.x + originalX);
  },
  onDragEnd: function () {
    oldX = objLineDivider.getAttribute("x1");
    endX = this.endX;
  }
});

// Calls with draggable scope
restore.call(draggable);

 

About call...

https://medium.com/@owenyangg/javascript-call-apply-and-bind-explained-to-a-total-noob-63f146684564

 

  • Like 1
Link to comment
Share on other sites

The easiest way to get the x value is to just reference the draggable instance.

 

var draggable = new Draggable(objTextHandle, {
  bounds: "#rectBA",
  onDrag: function () {
    objLineDivider.setAttribute("x1", this.x + originalX);
    objLineDivider.setAttribute("x2", this.x + originalX);
  },
  onDragEnd: function () {
    oldX = objLineDivider.getAttribute("x1");
    endX = this.endX;
  }
});

console.log("X", draggable.x);

 

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