Trigger the SVG animation manually using JavaScript

Update from 2022 March:

For a complete control over your animation from JS code, see SVGator's Player API:

This post describes how to start Your animation mapped to a custom event by using SVGator Player JS API, when the animated SVG is included in an object tag.

Please note that (due to security limitations) the JavaScript commands below will not run on a local index.html file but only through a web server, so we put together a minimalist example called trigger-animation, published on GitHub, which You can clone. It includes a basic http-server that loads the index.html with an animated SVG and a button that triggers the animation.

First, let's include the SVG animation within an object tag:

<object id ="animated-svg" type="image/svg+xml" data="animated.svg"></object>

Next, let's find the given object from JavaScript:

const svgatorObject = document.getElementById('animated-svg');

Then access its internal document:

const svgatorDocument = svgatorObject.contentDocument || svgatorObject.contentWindow.document;

To be noticed though that this approach will only work within the same domain, different domains following to be handled in the next release of the API.

Copy the ID from the beginning of the exported SVG file that looks like this:

<svg id="e5478wvxh25l1">
    ................
</svg>

Please note that the id property will be different in your case, so change it accordingly.

Use the id to access the SVG element:

const svgatorElement = svgatorDocument.getElementById('e5478wvxh25l1');

You can start the animation triggered by any custom event using the JS Player API, by simply calling the play method:

svgatorElement?.svgatorPlayer?.play();

To make sure svgatorPlayer is ready when the custom event triggering the animation  occurs, one can wrap the previous call in the player's ready method:

svgatorElement?.svgatorPlayer?.ready(player => player.play());

Before the JS Player API release, one could achieve the same effect using a roundabout solution, namely exporting the animation to start on the click event, then dispatching the given event on the SVG node, as follows:

svgatorElement.dispatchEvent(new Event('click'));

Now your SVG will animate every time you dispatch a click event.

We hope this helps!


Still got questions? Send us an email to contact@svgator.com and we will get back to you as soon as we can.