Embedded Scripting
Adding a script block directly into an SVG document does not differ from how we add one to an XHTML document. Both are XML-based, and both require that the actual script be contained in cdata opening and closing tags or the XML won't validate. Browsers provide access to the DOM though the top-level document differs. Both can be used to create, modify, remove, or animate existing document elements.
Example 12-5 shows a standalone SVG document with embedded script. The high-level document is the svg element. Just as with an XHTML or HTML document, the high-level window object is accessed for its onload event and used to set the onclick event on the SVG circle. Clicking on the circle shrinks the radius by 10 pixels between each click, until the circle effectively disappears.
Example 12-5. Scripting block embedded in SVG
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
width="600" height="600">
<script type="text/ecmascript">
<![CDATA[
// set element onclick event handler
window.onload=function () {
var circle = document.getElementById('redcircle');
// onclick event handler, change circle radius
circle.onclick = function() {
var r = parseInt(this.getAttribute("r"));
r-=10;
circle.setAttribute("r",r);
}
}
]]>
</script>
<circle id="redcircle" cx="300" cy="300" r="300" fill="red" />
</svg>The page works with Opera and Firefox, but not with IE, not even when accessed as the proper