Tips for creating a dynamic variable for an object key in jQuery to streamline your code

Utilizing the TweenMax library, I am adding styles to a div while scrolling. However, I am facing a challenge where I need different styles based on varying page resolutions. To address this issue, I implemented an if condition. Is there a way I can use a variable to streamline the code within the if block? I attempted using $direction and simply direction as variables, but it appears to be ineffective.

if (($(window).width() <= 900) && ($(window).width() >= 409)) {  
    var $direction = 'left';
} else {
    var $direction = 'top';
}
$(".softwares").children(".row").each(function(a) {
     $(this).delay(150 * a).fadeIn(0, function() {
         TweenMax.to($(this), .3, {
            $direction: 45 * a,
            opacity: 1,
            ease: Back.easeOut
         })
     })
});

After exploring numerous queries on Stack Overflow, I tried implementing [] to resolve the issue, but unfortunately, it didn't work as expected.

I aim to avoid incorporating additional code like the following:

$(".softwares").children(".row").each(function(a) {
     if (($(window).width() <= 900) && ($(window).width() >= 409)) {  
         // opacity: 1, ease: Back.easeOut are extra codes in both conditions
         var options = {left: 45 * a, opacity: 1, ease: Back.easeOut};
     } else {
         var options = {top: 45 * a, opacity: 1, ease: Back.easeOut};
     }
     $(this).delay(150 * a).fadeIn(0, function() {
         TweenMax.to($(this), .3, options) // use options object here
     })
});

Answer №1

One way to accomplish this is by following this method:

$(".software-list").children(".item").each(function(index) {
     if (($(window).width() <= 900) && ($(window).width() >= 409)) {  
         // Set options object directly within the condition
         var options = {left: 45 * index, opacity: 1, ease: Back.easeOut};
     } else {
         var options = {top: 45 * index, opacity: 1, ease: Back.easeOut};
     }
     $(this).delay(150 * index).fadeIn(0, function() {
         TweenMax.to($(this), .3, options) // Utilize options object here
     })
});

However, be aware that this approach may require writing some extra code.

Alternatively, you can explore this question for additional insights on working with dynamic keys in JavaScript objects.

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

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

What could be causing this ajax function to fail?

I referred to a solution in response to this question: My objective is to execute a query on the database when a user clicks on a specific table row, enabling me to retrieve and display their information. Below is the piece of code I am using: AJAX: $( ...

Unable to access the contents of an array (React JS)

After fetching the content as an array and viewing its contents with console.log, I noticed that despite the array being populated, it has a length of 0, making it impossible to retrieve its elements using map. What could be causing this issue? https://i. ...

The step-by-step guide to testing an Angular promise using Jasmine

An issue arises when attempting to test the code below using Jasmine, as the console.log in `then` is never called. The question remains: is this problem related to Angular or Jasmine? describe("angular test", function() { var $q; ...

Why isn't P5.JS's .display() working like it should?

I'm having trouble figuring out the scope of this code. I moved the function around, but I keep getting a "not a function" error. let bubbles = []; function setup() { createCanvas(400, 400); for (let i = 0; i < 10; i++){ bubbles[i] = new Bubbl ...

Ace code editor: A guide to implementing hover error messages

Using an Ace editor, I want to enhance my website by highlighting specific code ranges and displaying error messages when they are hovered over, just like in the example image. I'm curious if this functionality can be achieved through the Ace editor ...

MUI Alert: Encountered an Uncaught TypeError - Unable to access properties of undefined when trying to read 'light' value

After utilizing MUI to create a login form, I am now implementing a feature to notify the user in case of unsuccessful login using a MUI Alert component. import Alert from '@mui/material/Alert'; The code snippet is as follows: <CssVarsProvide ...

How to center the navigation list vertically with double lines and maintain the href block?

Looking for a solution to align vertically in a basic navigation list bar, particularly when some items have two lines of text. I want the text to be vertically aligned to the middle, while still maintaining the ability to hover and click within the list ...

My DIV elements are not responding to the widths I set for them. What could be the issue?

Recently, I've been delving into the world of Flex to experiment with some unique layouts. However, I encountered an issue where my divs were not recognizing widths as expected. I attempted to set the first div of each row to 5% width so they would ...

VueJS: Send all unspecified attributes to child component in the same way as using v-bind="$props"

I am looking for a way to receive any props passed by the parent component into the child component without explicitly mentioning them in props:[]. This is because I may not always know which props will be bound. Parent component <template> <di ...

What is the most efficient way to loop through an array and send each item to a method, ensuring that all methods are executed synchronously?

I need to make a request method call that retrieves its own body as an array, which is one item within another array. To achieve this, I have to iterate over the parent array and pass each of its items to the request method for a new server request. I tr ...

Personalized text hues for your WordPress product page

As someone who is new to all of this, please keep that in mind :/ I decided to remove the "add to cart" button from my theme (blocksy) so I could insert my own buttons within the product page under the "short description" text. I needed two "download" but ...

apply a course to the designated element

Alright, I have this piece of code that deals with session and page requests. // Let's start our session session_start(); // Now let's check if there is a page request if (isset($_GET['page'])) { // If there is a requested page, we ...

Retrieving XML data from an external API is essential for integrating information

For a personal project, I am working on a mashup and trying to integrate a webservice that I came across. You can find the webservice here: Whenever I attempt to call it via ajax (using FireFox 7 in this case), I constantly encounter the following error ...

The IMDB API is throwing a GraphQL error that says, "ClientError: Unable to retrieve information on the field 'Image' for the type 'MainSearchEntity'."

Seeking suggestions for the top 10 movies related to 'Africa' using the IMDB API demo available here. In my query, I am looking for movie id, title, poster image, and filming location. However, I encounter an error message 'ClientError: Ca ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

Incorporating an HTML page into a dialog using AngularJS: A step-by-step guide

Is it possible to dynamically change the content of a dialog by updating the URL? I have multiple HTML pages that I want to display in my dialog by simply changing the URL. <md-button ng-click="showDialog($event,'myurl/page-1.html')">Show ...

Utilize Mongoose's post method to generate a fresh collection without any data

Libraries in use: Express, Mongoose, Express-Restify-Mongoose Challenge: I am currently exploring the process of creating a POST request that involves providing the schema within the req.body. My goal is to seamlessly generate a new collection if it doesn ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...