0

I use vivus.js to animate SVGs. I wonder what is the best way to use it in combination with intersection observer, concerning performance.

On my page are several sections, including inline svgs. These svgs should be animated when scrolling down the page, stop when leaving the viewport und start again when the container is observed again.

It works but i am not sure if this is the best way to build vivus objects und play them again and again in this way. These solution seems to crash firefox performance..

I welcome all comments, suggestions and proposed improvements.

$( document ).ready(function() {
    //Define observed Items
    var myItems = document.querySelectorAll(".observed-item");

    //Define observer Options
    var observeroptions = {
        root: null,
        rootMargin: "-35% 0% -35% 0%",
        threshold: 0,
    };

    //Create new Observer Object
    var observer = new IntersectionObserver(function(entries, observer){
        entries.forEach(function(entry){

//Define Index Variable
var myIndex = $(entry.target).index();


var myvivus = new Vivus("item-svg" + myIndex, {
                    duration: 150,
                    start: 'manual'
                },
                function () {
                   $(entry.target).addClass('callback-item-animation');
                }
            )


            if (entry.intersectionRatio > 0) {

                //Add class to Entry Target
                $(entry.target).addClass("item-animate");
                myvivus.reset().play();

} else {
//Remove animated Class from observed Item
                $(entry.target).removeClass("item-animate");
                myvivus.stop().reset();

            }

        });
    },observeroptions);

    myItems.forEach(function(myItem) {
        observer.observe(myItem);
    });

});

I created a pen:

https://codepen.io/Milenoi/pen/JBxgOG

Please Note: without Polyfill works in Chrome + Firefox

As you can see, the animation doesn't work as expected, the svg animation should stop when leaving observer and start again wenn element is intersected again..

1 Answers1

0

Your hoisting observer and clashing it in the function. Add var or let before observer =, then change the name of observer in that function to something unique. Also qualify everything with window. Or context. That should improve the performance marginally

Jay
  • 3,276
  • 1
  • 28
  • 38
  • I did not poste my complete code. The observer is wrapped in $( document ).ready(function() { ... i will use var as you suggested but my main problem is the animation of the SVGs. i have no idea how to define a vivus object, to start or reset or stop it in combination with intersection observer. –  Aug 12 '18 at 13:48
  • I did the best I could with that which i had to respond. Let me know where you still need help as what I'm telling you still seems to apply. – Jay Aug 12 '18 at 13:50