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

The premature firing of the fireContentLoadedEvent in Internet Explorer is causing issues

I've encountered a strange issue with IE8 recently. My code has been functioning properly for a while and still works perfectly in Firefox, but all of a sudden Prototype has stopped calling my event listeners for dom:loaded. I typically attach them u ...

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

Error message: IndexError: list index out of range while attempting to trigger a click event using selenium

There are a total of 41 category checkboxes on the page, with only 12 initially visible while the rest are hidden. To reveal the hidden checkboxes, one must click on "show more." This simple code accomplishes that: [step 1] Loop through all checkboxes >> ...

Using $q.all function in a controller to fetch data from a service and receiving an

For a considerable amount of time, I have been facing some challenges with an API call. Even though the console.log in my service is returning the necessary data, the controller seems to receive an empty object. I suspect there might be an issue with how I ...

Issues with external javascript link functionality

I'm having trouble connecting my external JavaScript file to my HTML code. I'm attempting to concatenate two strings using an input function and then display the new string in the empty text field. What could be causing this issue? Appreciate an ...

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Vue is set up to monitor changes in two connected input fields for user input exclusively

Two input fields are available, where the value of one can affect the other. If a value between 1 and 200 is entered in the level field, Vue will look up the corresponding points for that level and populate the points field with them. Conversely, if a us ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Ensure the date is displayed in the format of dd-mm-yyyy when using the input type=date

Here is the code I am currently using : <input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" max=<?php echo ...

Increase the padding on the left side of a background image

UPDATE: Solution discovered at this link thanks to Mr. Alien I am attempting to create a heading that resembles the following Title ------------------------------------------------- I have an image that I intend to use as a backdrop for it. However, I& ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

Leveraging the keyword 'this' within an object method in node's module.exports

My custom module: module.exports = { name: '', email: '', id: '', provider: '', logged_in: false, checkIfLoggedIn: function(req, res, next){ console.log(this); } }; I inclu ...

Is there a Wordpress floating bar similar to the one seen on 9gag?

After browsing through some posts on stackoverflow, I noticed that my website is not responding as expected. You can check out my site here: To troubleshoot, you can examine the source code and utilize Firebug to inspect the css and javascript being used ...

The sequence of Angular directives being executed

When multiple directives are applied to an element in AngularJS, what determines the order in which they will be executed? For instance: <input ng-change='foo()' data-number-formatter></input> Which directive, the number formatter ...

Incorrect Reactjs installation technique

When I try to run create-react-app on my Windows PC, only dependencies are being installed with no folders other than node_modules. Even when using Yarn, I haven't been able to progress further. Please assist and thank you in advance for any help. Thi ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

What is the best way to position a small image within a menu?

Is there a way to adjust the position of the arrow image within the <li> element without affecting the layout of the unordered list? Below is the code snippet for reference: body { margin: 0; padding: 0; } nav { width: 100%; background: # ...

Repetitive invocation of functions

I am presenting a listing HTML structure as follows <li class="game-box showlist" id="papp_1249" data-tag="Junior KG,Maths"> <div class="game-box-link" data-id="1249" data-active="yes" data-orientation="landscape" data-ajax="fal ...