Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass variable as associative array field name

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading