SVG Home • SVG Tutorials • Scripting
Mouse-over each of these circles
If you try moving your mouse-pointer over and then off either of the circles above, you should notice the circle changing size and color. Both of these circles are SVG files which use ECMAScript, one common variety of a language sometimes referred to generically as "JavaScript". As with the use of scripting in HTML, so it is with ECMAScript in SVG: you can embed the script inline (the script code is in the SVG file) or you can refer to the script with an xlink:href attribute (the script code is an external file).
The mouseover/mouseout events for the dot on the left are handled by ECMAScript inlined into the SVG file. The mouseover/mouseout events for the dot on the right are handled by ECMAScript stored in an external file. The code for all three files is displayed below.
So why might we want to keep a script file separated from the SVG file?
|
|
clickScript_internal.svg
<?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
<!DOCTYPE svg
PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/SVG/DTD/svg10.dtd" >
<svg
width="300" height="200" viewBox="0 0 300 200"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.0">
<title>ECMAScript Example: A Clickable Circle</title>
<script type="text/ecmascript">
<![CDATA[
function setSize( evt, circleSize ) {
var circle = evt.getTarget();
circle.setAttribute( "r", circleSize );
}
function setLocation( evt, newX, newY ) {
var circle = evt.getTarget();
circle.setAttribute( "cx", newX );
circle.setAttribute( "cy", newY );
}
function setStyle( evt, newStyle ) {
var circle = evt.getTarget();
circle.setAttribute( "style", newStyle );
}
]]>
</script>
<circle cx="150" cy="100" r="25" fill="green"
onmouseover="setSize( evt, 50 ); setStyle( evt, 'fill: red;' );"
onmouseout="setSize( evt, 25 ); setStyle( evt, 'fill: green;' );"/>
</svg>
|
|
|
clickScript_external.svg
<?xml version="1.0" encoding="iso-8859-1" standalone="no"?>
<!DOCTYPE svg
PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/SVG/DTD/svg10.dtd" >
<svg
width="300" height="200" viewBox="0 0 300 200"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
version="1.0">
<title>ECMAScript Example: A Clickable Circle</title>
<script type="text/ecmascript" xlink:href="scripts/changeCircle.js"/>
<circle cx="150" cy="100" r="25" fill="green"
onmouseover="setSize( evt, 50 ); setStyle( evt, 'fill: red;' );"
onmouseout="setSize( evt, 25 ); setStyle( evt, 'fill: green;' );"/>
</svg>
changeCircle.js
function setSize( evt, circleSize ) {
var circle = evt.getTarget();
circle.setAttribute( "r", circleSize );
}
function setLocation( evt, newX, newY ) {
var circle = evt.getTarget();
circle.setAttribute( "cx", newX );
circle.setAttribute( "cy", newY );
}
function setStyle( evt, newStyle ) {
var circle = evt.getTarget();
circle.setAttribute( "style", newStyle );
}
|