[SOLVED] How to pass variable as associative array field name

Issue

Let’s assume I have an Angular project, where I want to animate a clicked element (having position: relative) with jQuery and pass the direction of the animation with a parameter variable like below;

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

The code above gives a dir=20 attribute to the target HTML element which is not the desired behavior. I think the compiler does not interpret dir as a variable, it is rather just perceiving a ‘dir’ string there.

I am unsure whether the above is the result of combining jQuery and TypeScript, but I have to use variables to determine the animation direction, what am I doing wrong here?

How to make the compiler using dir as a variable, rather than just text?

Solution

You can use computed property names to get the behavior you want during object initialization.

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

It can also be done post-creation, something like this:

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

Answered By – Octavian M─ârculescu

Answer Checked By – Willingham (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *