|
SVG Basics - JavaScript in SVG
|
|
Published
07/17/2006
|
SVG Viewer
|
|
|
|
|
|
JavaScript in SVG
The other sections of the tutorial deal with how to use SVG to make beautiful shapes. In this section, let's put those shapes to work doing some real work by using Javascript to glue them together. Most SVG viewers support JavaScript (ECMAScript) as their main scripting language but SVG is not limited to only that language.
JavaScript can either be embeded or in an external file. The next code example shows both styles.
<script type="text/ecmascript" xlink:href="unseth/unseth.js" />
<script type="text/ecmascript"><![CDATA[
...
]]></script>
Code 1. Adding JavaScript (EcmaScript) to a SVG document.
To preform an action when an event occurs you just add the event handler to the associated object. This is much like HTML except the event names must be all lowercase letters.
| Event | When Called |
| onclick | When the object is clicked (mouse button down and up) |
| onmousedown | When the mouse button is pushed down on the object |
| onmouseup | When the mouse button is released on the object |
| onmouseover | When the mouse cursor moves over the object |
| onmousemove | When the mouse moves in the object |
| onmouseout | When the mouse cursors leaves the object |
Table 1. Events for Graphical Elements.
| Example | Code |
| <script type="text/ecmascript"> <![CDATA[ ... function updateStats() { svgDocument.getElementById("clicks").firstChild.data = "onclick = " + click; svgDocument.getElementById("mousedowns").firstChild.data = "onmousedown = " + mouseDown; ... } function msClick (evt) { click++; updateStats(); } ... ]]> </script> <circle cx="50%" cy="25%" r="40" fill="lightyellow" onclick="msClick()" onmousedown="msDown()" onmouseup="msUp()" onmouseover="msOver()" onmousemove="msMove()" onmouseout="msOut()" /> |
Example 1. Calling a function on an event.
(Download)
The Batik SVG viewer sets the variable "window.document" to be the SVG document root and is incompatible with the above code.
If SMIL animation doesn't quite handle how you want to animate something in SVG then the alternative is using JavaScript (EcmaScript). SMIL animation is very handy but there are plenty of behaviours that can be much more easily modeled by using JavaScript.