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.
|