Lawston Posted April 7, 2021 Share Posted April 7, 2021 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 More sharing options...
PointC Posted April 7, 2021 Share Posted April 7, 2021 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. 2 Link to comment Share on other sites More sharing options...
OSUblake Posted April 7, 2021 Share Posted April 7, 2021 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 1 Link to comment Share on other sites More sharing options...
Lawston Posted April 7, 2021 Author Share Posted April 7, 2021 Fantastic, as always, sir. I see it plainly now and am a little embarrassed it took me this long. Many thanks. Link to comment Share on other sites More sharing options...
OSUblake Posted April 7, 2021 Share Posted April 7, 2021 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); 2 Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now