user3376065 user3376065 - 6 months ago 41
Javascript Question

Bodymovin loop a segment on demand

I have several icons that have an intro animation [0,20] where they get drawn in and a loop animation [21, 100] for when you hover over the icons. Setting loop to true will make all my segments loop which is not what I want, I only need one of the segments to loop. Anyway do this?

Here's an example of how I have my code setup:

var data = {
container: el,
renderer: 'svg',
loop: false,
autoplay: false,
path: 'data.json'
};

var anim = bodymovin.loadAnimation(data);

anim.addEventListener('DOMLoaded', function(e) {
anim.playSegments([0,20], true); // run intro animation
});

el.addEventListener('mouseover', function(e) {
anim.playSegments([21,100], true); // run loop animation
});


Final Answer Edit:

My implementation was inspired by but a bit different from the correct answer so I thought it was worth mentioning. I basically load the same animation into two elements that are placed on top of each other. The two DOM elements are toggled via CSS for default and hover modes. The only difference is that I manipulate the data object and change the loop to true for the hover effect! So I found no need to go back to my animator and ask them to split the animations into different files.

Answer Source

You need to get your animation split into 2 files, say intro and hover. This gives you the ability to control which section is to loop.

So the intro file could be:

var dataIntro = {
      container: el,
      renderer: 'svg',
      loop: false,
      autoplay: false,
      path: 'dataintro.json'
    };

var animIntro = bodymovin.loadAnimation(dataIntro);

animIntro.addEventListener('DOMLoaded', function(e) {
    animIntro.playSegments([0,20], true); // run intro animation
});

and repeat for the dataHover file:

var dataHover = {
      container: el,
      renderer: 'svg',
      loop: true,
      autoplay: false,
      path: 'datahover.json'
    };

var animHover = bodymovin.loadAnimation(dataHover);

el.addEventListener('mouseover', function(e) {
    animHover.playSegments([0,79], true); // run loop animation
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download