blue bar

Home  |  Resources SiteMap  

blue bar
   Dynamic SVG > Interactivity > Using Javascript

Print Version       Previous       Next       

Interactivity - Using Javascript

Code Example

SVG Image

<?xml version="1.0" standalone="no"?>

Right-click on the image to open the SVG viewer pop-up menu.
Click 'view SVG' to display the image in a new, full window to zoom & pan the image.  (SVG Viewer Tips)

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<svg width="500" height="500">

<!-- Javascript -->
<script type="text/javascript">
<![CDATA[
var redVal=0;
var greenVal=0;
var blueVal=0;
function changeCol(evt)
{
var targetshape= evt.getTarget();
redVal = Math.round(Math.random()*255);
greenVal = Math.round(Math.random()*255);
blueVal = Math.round(Math.random()*255);
targetshape.setAttribute("fill","rgb(" + redVal + "," + greenVal + "," + blueVal + ")");
}
// ]]></script>

<!-- Draw a Circle -->
<circle cx="90" cy="90" r="70" fill="blue" onclick="changeCol(evt)" />

</svg>

Code explanation

In this example, when we click on the circle, its fill changes to a random color on each click.

1. The first step of scripting SVG with Javascript is to inform the viewer that you are now working in a scripting language. To define which scripting language you are coding, the type attribute is set to text/javascript.

2. <![CDATA[ is the XML command that tells the viewer to stop parsing the code and read the code within the block that follows as character data. This prevents the viewer from processing brackets and other special characters as SVG elements, and makes it easier for you to write your scripts.

3. Inside the script, three variables are defined: redVal, greenVal, and blueVal. These variables hold the red, green, and blue values, respectively, that you will use in your function. This function is called changeCol and takes in the parameter (evt). The evt is a reserved SVG word that describes the event that has just happened. Here, the evt method is called getTarget(); this method returns a reference to the SVG object that triggers the event. This reference is then stored in the variable targetShape.

4. Three random numbers with values between 0 and 255 are generated by a simple JavaScript Math function.

5. Finally, the setAttribute method is called on targetshape. The object's fill attribute is set to an RGB value (such as rgb(150,200,50)) using the three random numbers generated in the previous step.

6. After you close off the CDATA block and script, you return to SVG. A circle is drawn, and through the onClick element, it calls the function changeCol(evt) when clicked.

Previous       Next       

   
 

About the Tutorial

 

SVG Overview

 

SVG Basics

 

Basic Drawing

 

Painting & Effects

 

Dynamic SVG

 

Animation

 

Interactivity

    Basics
    Linking
    Mouse Event
    Keyboard Event
    Scripting
    Using Javascript
  Quiz