Tips for accessing associative array elements using variables as field names

Imagine you have an Angular project and you want to animate a clicked element with jQuery. The element has a position: relative. You decide to pass the direction of the animation using a parameter variable as shown in this example:

onClickFoo(event :MouseEvent, dir :string) :void {
   let targetId :string = (event.currentTarget as Element).id;
   $("#" + targetId).animate({
      dir: "20px"
   });
}

The issue here is that the code ends up assigning a dir=20 attribute to the HTML element instead of interpreting it as a variable. It seems like the compiler is treating 'dir' as a string rather than a variable.

This problem might be caused by the combination of jQuery and TypeScript. If you need to use variables to determine the animation direction, what could be going wrong in this scenario?

Is there a way to make the compiler recognize dir as a variable, rather than just plain text?

Answer №1

If you want to achieve a specific behavior during object initialization, you can utilize computed property names.

$("#" + targetId).animate({
  [dir]: "20px"
});

Alternatively, you can also implement this behavior after the object has been created:

onClickFoo(event :MouseEvent, dir :string) :void {
   let targetId :string = (event.currentTarget as Element).id;
   const animationProps = {};
   animationProps[dir] = "20px";
   $("#" + targetId).animate(animationProps);
}

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 CSS and JavaScript in pure form are not functioning properly upon deployment in Django

In my Django project, I am utilizing pure CSS and Bootstrap. Everything appears as expected when I test it on my local machine. However, once deployed, the appearance changes. The font looks different from how it did before deployment: After deploying to ...

Trigger a jQuery event when an element is moved to a new line

Is there a way to trigger a jQuery event when an element moves to a new line in the view? I want to hide navigation items and run additional JavaScript code when this happens. Any ideas on how to achieve this? Here's how my navigation appears in a wi ...

What is the best way to incorporate a designated waiting period into the fulfillment of a promise?

I want to create a function that can take a promise and return another promise that resolves after a specified timeout period. Here is an example of what my code looks like, but I'm uncertain if I am handling all cases properly. // Function that retu ...

Calculate a range while meeting a specific condition using JavaScript

I am currently working on a project in node.js involving the leap motion technology. I need to create a counter that increments by +1 inside a span element every time the numberOfFingers property of a user's hand is equal to 5. Can someone provide gui ...

Rotating a loaded file using THREE.js

After experimenting with the ThreeJS library for a few weeks and drawing inspiration from others, I managed to create a canvas that displays an external .stl-file. However, my main issue is that I am struggling to apply any transformations to it. While I ...

Incorrect data is being shared through social sharing links

I'm having difficulty sharing my page on various social media platforms such as Twitter, Google+, Facebook, Pinterest, and Linkedin because it's not displaying the correct information. (I also plan to share dynamic data on inner pages once I&apos ...

Numerous memberships for a single assortment within MeteorJS

Currently seeking guidance on the most effective way to accomplish the following task using MeteorJS. The requirements are as follows: a list with items and a sidebar with a selected item (not necessarily from the current page of the list). https://i.sst ...

The 'in' operator cannot be used in Jquery to search for 'display' in a value that is undefined

This is the HTML code snippet I have: <div class="V_CPp Elss <?php echo $Show; ?>"> <span class="ViewC">View more comments</span> </div> <di ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

Sorting JSON arrays in Typescript or Angular with a custom order

Is there a way to properly sort a JSON array in Angular? Here is the array for reference: {"title":"DEASDFS","Id":11}, {"title":"AASDBSC","Id":2}, {"title":"JDADKL","Id":6}, {"title":"MDASDNO","Id":3}, {"title":"GHFASDI","Id":15}, {"title":"HASDFAI","Id": ...

The Combination of Bootstrap 4 and the jQuery Validation Plugin

Currently, I am in the process of working on a project that requires me to implement a simple form validation on the client side. After some research, I decided to use the jQuery validation plugin. While experimenting with some basic functionalities, I enc ...

The Great Gatsby - Unable to access property 'component---src-pages-index-jsx' due to its undefined nature

Attempting to transition my current ReactJS application with a WordPress backend to GatsbyJS has presented some challenges. As a newcomer to GatsbyJS, I diligently followed the setup instructions provided on their website for Windows 10. Despite a successf ...

Tips for implementing multiple nested routes using Vue.js?

Can Nested Routes be created with more than 2 levels? I am looking to implement a structure like this: +--------------------+ | User | | +----------------+ | | | Profile | | | | +------------+ | | | | | About | | | | | | +------ ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

I am attempting to swap values within table cells using AngularJS. Would it be recommended to utilize ngBind or ngModel, or is there another approach that would

How can I make a table cell clickable in AngularJS to switch the contents from one cell to another, creating a basic chess game? I want to use angular.element to access the clicked elements and set the second clicked square equal to the first clicked using ...

Add CSS file to the HTML head by substituting the <link> tag

Searching for a possible npm-based solution to replace: <link rel='stylesheet' href='style.css'> with <style><!-- actual contents of the style.css file here --></style> to simplify the process of building a l ...

Is there a way to extract data from a single line?

In my code, I have a simple object retrieved like this: getSelectedRecipients(event) { this.aliasesService.getRecipients(event.nr) .subscribe( res => { this.recipients = res; this.isVisible = true; }, err =&g ...

The issue with Vuex and Typescript is that when using mutation object payloads, they are consistently undefined

Every time I run my code, the object payload I'm passing as a secondary parameter to my Vuex mutation method ends up being undefined. Both my Vuex and component files are coded in TypeScript. When looking at my index.ts file for my Vuex store (where ...

Oops! There was an issue with building the module in ./src/index.js using babel-loader

I'm running into issues setting up ReactJs from scratch. Whenever I try to use npm start, dev, build, or watch, I encounter the error shown below: ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError ...

Gatsby Image Sharp Troubleshooting: Resolving Errors

My Gatsby v5 project, built using typescript, is encountering issues during compilation after running the initial gatsby new command. The compilation fails and I am presented with the following errors: load plugins dyld: lazy symbol binding failed: Symbol ...