Using GreenSock to animate and manipulate the tween function's parameters

I have two functions that are called on mouse events:

function menuBtnOver(e){
    var b = e.data;
    b.setPosition(b.x, b.y+5);
}

function menuBtnOut(e){
    var b = e.data;
    b.setPosition(b.x, b.y-5);
}

Additionally, there is another function:

setPosition:function(x, y) {
        if(!x) x = 0;
        if(!y) y = 0;
        this.element.css("left", x);
        this.element.css("top", y);
    }

The 'element' property mentioned above is a jQuery object. While the existing setup works fine, I am interested in adding animation. Is it possible to achieve this using TweenLite? I've experimented with different code snippets such as:

function menuBtnOver(e){
    TweenLite.to(e.data, 1, {top:500});
}

And also tried:

function menuBtnOver(e){
    TweenLite.to(e.data.getElement(), 1, {top:500});
}

However, none of these methods seem to be working as expected. The only method that somewhat works is:

function menuBtnOver(e){
    TweenLite.to(e.data, 1, {y:400, onUpdate:e.data.setPosition, onUpdateParams:[e.data.x, e.data.y]});
}

Although, it only works for the first button and encounters errors when trying to tween endlessly.

Uncaught TypeError: Cannot read property 'css' of undefined

This error occurs at:

this.element.css("left", x);

Update

After some investigation, I discovered the issue.

function menuBtnOver(e){
    TweenLite.to(e.data, 1, {y:400, onUpdate:e.data.setPosition, onUpdateParams:[e.data.x, e.data.y], onUpdateScope:e.data});
}

The problem here lies in the static values used for 'onUpdateParams'. To solve this, I modified the 'setPosition' function:

setPosition:function(x, y) {
    if(!x) x = 0;
    if(!y) y = 0;
    this.element.css("left", this.x);
    this.element.css("top", this.y);
}

Unfortunately, this workaround is not ideal. A potential solution could be:

 MenuButton.prototype = {
    setPosition:function(x, y) {
        if(!x) x = 0;
        if(!y) y = 0;
        this.x = x; this.y = y;
        this.element.css("left", x);
        this.element.css("top", y);
    },
    updatePosition:function(){
        this.element.css("left", this.x);
        this.element.css("top", this.y);
    }
}

function menuBtnOver(e){
    TweenLite.to(e.data, 1, {y:400, onUpdate:e.data.updatePosition, onUpdateScope:e.data});

}

Alternatively, an external update function could be defined in a similar manner. The main question remains whether there is a simpler approach to handle this scenario. Does GS Tween offer any automation for this process?

Thank you to everyone for your attention :)

Answer №1

this in the context of setPosition refers to the function itself, not the this from the onClick event.

To make it work correctly, you should pass this to setPosition. In the code snippet below, I used self as the parameter in the setPosition function:

function menuBtnOver(e){
  var b = e.data;
  b.setPosition(this, b.x, b.y+5);

}

function menuBtnOut(e){
  var b = e.data;
  b.setPosition(this, b.x, b.y-5);

} and:

setPosition:function(self, x, y) {
    if(!x) x=0;
    if(!y) y=0;
    self.element.css("left", x);
    self.element.css("top", y);
}

This concept of 'this' always points to the context in which it was called. You can find more information about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Remember, you can pass this as a variable in functions.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using an external function to implement Javascript and AJAX interactions

function makeAjaxRequest(destination_full_url) { if (window.XMLHttpRequest) {// code for modern browsers xmlhttp = new XMLHttpRequest(); } else {// code for old Internet Explorer versions xmlhttp = new ActiveXObject("Microsoft.XMLH ...

Material-UI: Issues with functionality arising post library update

I recently switched from material-ui version 0.14.4 to 0.15.4 and encountered some issues while trying to make my code work. Below is an excerpt from my code: var React = require('react'), mui = require('material-ui'), LoginDialog ...

Encountering a ReferenceError: require is undefined error when utilizing contextIsolation: true in conjunction with a preload script

My goal is to implement a select folder popup functionality, and I have written the following code for this purpose. Within the create-window.ts file, I have included these browserOptions.webPreferences: webPreferences: { nodeIntegration: true, conte ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

Prevent Material UI Chips from altering color upon activation

Chip number 3 in the image below appears with a slightly darker background color when clicked, but this change is unnecessary as only the delete button has functionality. Therefore, the change in color serves no purpose. How do I prevent the background co ...

Am I on the right track with my service definition in Angular?

(function(){ angular.module('myApp',[]) })(); (function(){ angular.module('myApp.dashboard',[]) })(); (function(){ angular.module('myApp.value',[]) })(); (function(){ 'use strict'; angular.modu ...

when successful, refresh the page

I am currently utilizing the following javascript code to load recrefresh.php when the page first loads. Upon executing the ajaxvote function, I aim for the subsequent div to be refreshed: <div class="recrefresh"></div> After attempting to ad ...

The ng-if directive in AngularJS seems to be malfunctioning

Could someone please help me understand why my "Voted:" checkbox is not controlling the ng-if directive? Strangely enough, the "Keep HTML" checkbox is working fine. <p> <li ng-repeat="x in info"> {{x.name}} Voted: <input type="c ...

Safari is experiencing issues with overflow-x functionality after a device rotation

I'm currently in the process of developing a website that requires a specific div element to be horizontally scrollable if its content exceeds the screen size. This functionality works smoothly on most browsers, except for Safari: Scenario: When the ...

Search for Instagram images with a specific tag using jQuery and AJAX

I am looking to create a feature where users can enter a tag and view recent media related to that tag. I attempted to implement this code but encountered an error in the Chrome Console. "https://api.instagram.com/v1/tags//media/recent?callback=jQuery2240 ...

What is the best approach for creating a Pagination component in React JS?

I recently started developing a web-app and I'm still learning about web development. I have received a backend response in JSON format with pagination information included: { "count": 16, "next": "http://localhost:800 ...

The d3.js Time Scale Chart is facing issues when rendering with Array object values, unlike static values which render the chart perfectly

Generating an Array Dynamically with N objects from a JSON File var taskArray = []; d3.json("input.json", function(error, json) { if (error) return console.warn(error); for ( var i = 0; i < json.length; i++) { ...

Modifying icons with JavaScript

When I click on the play icon, it changes to the pause icon. However, I am only able to change the first icon from play to pause in my JavaScript code. How can I apply this functionality to all the audio elements on the page? let playIcon = "https://ima ...

Getting a ReferenceError while trying to use a MongoDB Collection variable in an external resolver file that had been imported through mergeResolvers

Here is a simplified example to illustrate the issue at hand. When using the resolver Query getAllUsers, the MongoDB Collection Users is not accessible in the external resolver file user.js. This results in the following error when executing the query: ...

Bordering the isotopes

Currently, I am utilizing a plugin that involves the isotope filter library. By setting the width to 33.33%, my list elements are organized into 3 columns. I am trying to specify the middle column to have side borders. However, whenever I click on the filt ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Interacting with a RESTful Service on a separate server

I need assistance with a JavaScript method snippet that I have included below: var tempUrl = "http://A.com:8081/TestService/serviceMethod"; jQuery.ajax({ url:tempUrl, type: 'POST', data:"getDatareq="+encodedata, contentType: 'app ...

How can I switch between columns in a dual-column layout?

In my latest project, I utilized CSS Flexbox to create a sophisticated two-column layout that allows toggling each column independently. While this functionality is exactly what I need, I can't help but feel that my current method is somewhat cumberso ...

The nth-child selector fails to function properly with a customized MUI component in CSS

I've created a styled component as shown below: const FormBox = styled(Box)(({ theme }) => ({ width: "47vw", height: "25vh", backgroundColor: theme.palette.grey[100], borderRadius: theme.shape.borderRadius, marginLeft: ...

Combining Three.js with iFrame for a mix of WebGL and CSS3D

After some experimentation, I successfully created a dynamic page that seamlessly integrates WebGL and CSS3D (with valuable guidance from this helpful SO post). To add an extra touch, I included an iframe: However, I noticed that the functionality to inte ...