Triggering KeyshapeJS Animations on Mouse Over

This tutorial shows how to play a KeyshapeJS animation on mouse over using the public KeyshapeJS API. Below is a live example of such animation.

The animation has been exported from Keyshape so that it plays only once (export setting Loop: Play Once).

Note that mobile devices don’t have a mouse, so some mobile web browsers simulate it. On Android, when the tickbox is touched to receive the focus, the animation plays. On iPhone, the animation never plays. See the bottom of the page for a consistent solution for mobile devices.

The Code

The HTML code for the animation uses the <object> element and a small piece of script.

<object data="tickbox.svg?global=paused" type="image/svg+xml"
onmouseover="playAnimation(this)"></object>
 
<script>
function playAnimation(obj)
{
if (obj.contentDocument && obj.contentDocument.ks) {
var ks = obj.contentDocument.ks;
if (ks.timelines()[0].state() != "running") {
ks.timelines()[0].time(0);
}
ks.globalPlay();
}
}
</script>

HTML

The HTML <object> element is used to embed the animation on the web page. The <object> element has to be used instead of the <img> element so that web browsers can run the JavaScript animation in the SVG file. The data attribute has the name of the SVG file “tickbox.svg” with a parameter “?global=paused” to pause the animation when it is loaded. Otherwise, the animation would play immediately when the page is loaded.

The element uses the onmouseover attribute to play the animation on mouse over.

The script checks that the SVG file has been loaded. Then it sets the animation time to zero if it isn’t running. This is needed to restart the animation if the mouse is hovered over the animation multiple times.

The last script line makes the animation play until it finishes.

The code has been designed so that it is easy to add more SVG animations to the page. Just add more <object> elements and they will use the same script to play the animations on mouse over.

Mobile Devices

By default, Android and iPhone behave differently for mouse over events. It is possible to make them consistent so that they always play the animation when the SVG graphics is touched.

Here’s an example and code. It adds an additional touch event listener for the SVG graphics to trigger the animation.

<object data="tickbox.svg?global=paused" type="image/svg+xml"
onmouseover="playAnimation(this)" onload="playAnimationOnTouch(this)"></object>
 
<script>
function playAnimation(obj)
{
if (obj.contentDocument && obj.contentDocument.ks) {
var ks = obj.contentDocument.ks;
if (ks.timelines()[0].state() != "running") {
ks.timelines()[0].time(0);
}
ks.globalPlay();
}
}
function playAnimationOnTouch(obj) {
if (obj.contentDocument) {
obj.contentDocument.documentElement.addEventListener("touchstart",
function() { playAnimation(obj); });
}
}
</script>

HTML

Document History

- Document created.