1

I'm trying to make icons animate when they are clicked. I would like the animation to complete before it can be restarted.

I build my icons first by selecting elements and then using their id's to load the animation data via the path option:

var icon_containers = document.querySelectorAll('div.icon');
var icons = [];

function buildIcons() {
    for (var i = 0; i < icon_containers.length; i++) {
        element = icon_containers[i];
        if (element.id !== '') {
            var params = {
                container: element,
                renderer: 'svg',
                loop: false,
                autoplay: false,
                path: element.id + '.json'
            };
            var anim = bodymovin.loadAnimation(params);
            icons.push({
                anim: anim,
                element: element,
                isPlaying: false
            });
        }
    }
}

buildIcons();

The icons object is then looped through and the animationStart method is called as well as a click handler added to each icon container:

function startAnimation(anim, icon) {
    anim.setDirection(1);
    anim.goToAndStop(1);
    anim.play();
    // This seems to fire immediately, before the icon has completed its animation?
    anim.addEventListener('loopComplete', complete(icon));
}

buildIcons();

icons.forEach(function(value, id) {
    startAnimation(value.anim, id);
    value.element.addEventListener("click", function(e) {
        startAnimation(value.anim, id);
    });
});

The startAnimation method attempts to attach an event handler to fire when the loopComplete event happens.

function complete(icon) {
    console.log(icon + ' loopComplete');
}

However this seems to fire immediately and I'd like to know how to make it fire after the animation so I can then not start a new animation until it has completed.

I've made a reduced test case here: https://codepen.io/paulyabsley/project/editor/ALEWnK

Docs for bodymovin.js: https://github.com/bodymovin/bodymovin

Yabsley
  • 380
  • 1
  • 4
  • 17
  • @NickA I don't think bodymovin.js has that event? – Yabsley Sep 13 '17 at 12:19
  • Yabsley, nevermind, I think I have an idea. You're using `addEventListener` incorrectly, you're supposed to pass it a function, but you're *calling* the function inside it. Change that line to `anim.addEventListener('loopComplete',function(){complete(icon)})` like you did further down. – Nick is tired Sep 13 '17 at 12:22
  • @NickA When I try that the event doesn't seem to fire at all. – Yabsley Sep 13 '17 at 12:32

0 Answers0