0

I am currently working on a project which has a lot of SVG animations. These animations need to be triggered when the user scrolls to the SVG.

I decided to create functions for each Snap.SVG animation and store them in an array of objects using the SVG's ID as the key like so:

//Example Object

var item = {
    aboutUsSVG: function(){
        //aboutUsSVG animation code to go here
    }
}

I have created a Codepen of my code so far here:

http://codepen.io/decodedcreative/pen/mEpZbx

I managed to create the array of objects fine. I have a second function which plays the animation when the SVG is on screen. I am having trouble accessing the animation function stored in the array using a dynamic key.

I can access the function if I know the name of the SVG like so:

var playAnimation = animations.animationsArray[0].ourCompanies;

playAnimation();

But I want to write a solution which can be used for all animations on the site so wish to query the DOM for the SVG ID and then lookup the corresponding animation.

So:

var animationID = $(this).find(".svg-animation svg").attr('id');
var playAnimation = svgAnimations.animationsArray[0].animationID;
playAnimation();

But in the code above animationID is being used literally and not being replaced by the aboutUs function.

I think this is a fairly common JS issue. Can anyone help?

James Howell
  • 1,392
  • 5
  • 24
  • 42

2 Answers2

1

To access a property of an array using a variable you need to use bracket notation:

var animationID = $(this).find(".svg-animation svg").prop('id');
svgAnimations.animationsArray[0][animationID]();
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You can use bracket notation to access object property with dynamic variable

check below code

var animationID = $(this).find(".svg-animation svg").attr('id');
var playAnimation = svgAnimations.animationsArray[0][animationID];
playAnimation();
Arif
  • 1,617
  • 9
  • 18
  • I definitely tried this and it didn't seem to work at the time. But another attempt has proved successful. Thanks guys – James Howell Jul 14 '16 at 12:04