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 HTML code for the animation uses the <object> element and a small piece of script.
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.
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.
- Document created.