SVG drawings can use JavaScript (ECMAScript) to do complex manipulation of the objects in the drawing. In this example, the style sheet of the last example is replaced by simple JavaScript calls. The Object Properties dialog ( → ( Shift+Ctrl+O )) can be used to add the calls.
To modify the previous example to use JavaScript, first
remove the style section (use the XML Editor
dialog). Next, open the Object Properties dialog. Select the
square (make sure the square is selected and not the <a>
wrapper, you can do this by first double-clicking the square and
then clicking on it again). Then click on the triangle next
to Interactivity in the Object Properties
dialog to expose the JavaScript options. Add the following
to onmouseover:
setAttribute('fill-opacity','1.0')
and the following to onmouseout:
setAttribute('fill-opacity','0.75')
. That's
it! Do not save as Plain SVG as the
JavaScript commands will be (erroneously) stripped out. You
can save it as Optimized SVG.
While the Object Properties dialog is open we can fill the title and desc attributes. These attributes can be specified for any object in an SVG document, including Groups. The title attribute is intended to be used for a tool tip. This is only implemented in some SVG browsers like Opera. (Firefox 3.5 will put in the window title area the first title found in the document). The desc (Description) attribute is used to store a description of the object. It is not normally intended for display. One final touch is to change the Id to a more descriptive name. You must click on the Set button for changes to these attributes to take effect.
<?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" version="1.1" width="150" height="150"> <a xlink:href="http://www.w3.org/" style="fill-opacity:0.75"><rect id="BlueRect" width="90" height="90" x="30" y="30" style="fill:#0000ff;stroke:#000000"
onmouseover="setAttribute('fill-opacity','1.0')"
onmouseout="setAttribute('fill-opacity','0.75')"> <desc id="desc3364">A clickable square to test simple JavaScript.</desc> <title id="title3362">Click square to go to http://www.w3.org.</title> </rect> </a> </svg>
Rectangle's default opacity. | |
Rectangle's style. Note that “fill-opacity” is not defined here. This allows class attributes to be overridden. | |
JavaScript calls for onmouseover and onmouseout. |
Note that some extensions for adding simple JavaScript are discussed in the section called “JavaScript”.
© 2005-2017 Tavmjong Bah.![]() | ![]() |