Triggering KeyshapeJS Animations When Scrolled Into View
KeyshapeJS SVG animations have a public API, which can be used to play and pause them. This tutorial shows how to trigger animations when they are scrolled into view. Scroll to the bottom of the page to see a live example.
We start by defining helper functions to make playing and pausing the animation easier. The SVG file may take a while to load on slow network conditions. These functions check that the file has already been loaded before calling the globalPlay() and globalPause() methods.
The next function checks if the given element is visible in the view. The margin variable can be used to adjust how much space there must be around the element before it is considered visible.
The last helper function is used to play the SVG animation if it is immediately visible after it has been loaded.
Adding the SVG Animation
Then, we use the <object> element to place the SVG animation on the HTML page. It has “global=paused” in its URL to prevent the animation from playing back immediately. The class name “scroll-activated” is set so that scripts can access it. It also has an onload event handler so that it starts playing if it is immediately visible on the page.
Scrolling to Play and Pause
We still need a way to track the page scroll position to play and pause animations. When the page is scrolled, the following code goes through all elements having the “scroll-activated” class and plays or pauses them based on their visibility.
More Than One Animation
The code has been written so that it is possible to have many SVG animations on the same page. Just add an <object> element with the “scroll-activated” class name and it gets played when it becomes visible.
Below you can see a live example. The animation plays only when it is completely in view. This animation loops forever, but it is possible to replace it with a non-looping animation.
- Document created.