Bodymovin hover playing animation only once
Asked Answered
T

2

10

Got my animation to trigger play on hover. I got everything to work but when I try to hover to play again, nothing seems to work.

Any ideas what I wrote wrong?

var squares = document.getElementById("test");
var animation = bodymovin.loadAnimation({
    container: test,
    renderer: "svg",
    loop: false,
    autoplay: false,
    path: "https://dl.dropboxusercontent.com/BodyMovin/squares.json"
});

squares.addEventListener("mouseenter", function () {
    animation.play();
});

function playAnim(anim, loop) {
    if(anim.isPaused) {
        anim.loop = loop;
        anim.goToAndPlay(0);
    }
}

function pauseAnim(anim) {
    if (!anim.isPaused) {
        anim.loop = false;
    }
}
Tweezers answered 3/8, 2017 at 17:24 Comment(0)
M
7

When the animation reaches it's final frame, it doesn't go back to the first one. That's why if you call play, nothing happens since it has already ended and there is no more to play.
You should do:

squares.addEventListener("mouseenter", function () {
  animation.goToAndPlay(0);
});

And if you only want it to replay once it has reached it's final frame, this should work:

var isComplete = true;
svgContainer.addEventListener('mouseenter', function(){
  if(isComplete){
    squares.goToAndPlay(0);
    isComplete = false;
  }
})

squares.addEventListener('complete', function(){
  isComplete = true;
})
Mansoor answered 29/10, 2017 at 0:58 Comment(0)
L
2

I'm giving a shot on this, although my experience about Bodymovin (and Lottie) is only from React Native world.

This should be quite straight forward to stop animation and restart it when cursor leaves the element:

squares.addEventListener("mouseenter", function () {
  animation.play();
});

squares.addEventListener("mouseleave", function () {
  animation.gotoAndStop(0);
});
Lyn answered 27/10, 2017 at 11:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.