Using JavaScript

New in v0.47

SVG drawings can use JavaScript (ECMAScript) to do complex manipulation of the objects in the drawing. In this example, the style sheet of the previous example is replaced by simple JavaScript calls. The Object Properties dialog 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). 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.

Object Properties dialog.
The Object Properties dialog showing the JavaScript additions (as well as the Title and Desc attribute additions).

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. You must click on the Set button for changes to these attributes to take effect.


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.0"
   width="150"
   height="150"
   id="svg1341">
  <defs
     id="defs1343" />
  <g
     id="layer1">
    <a
       xlink:href="http://www.w3.org/"
       style="fill-opacity:0.75"     1
       id="a1445">
      <rect
         width="90"
         height="90"
         x="30"
         y="30"
         style="fill:#0000ff;stroke:#000000;stroke-width:1px"     2
         id="rect1353"
         onmouseover="setAttribute('fill-opacity','1.0')"     3
         onmouseout="setAttribute('fill-opacity','0.75')" />
        <desc
           id="desc3364">A clickable square to test simple JavaScript.</desc>
        <title
           id="title3362">Click square to goto http://www.w3.org</title>
    </a>
  </g>
</svg>

  

1

Rectangle's default opacity.

2

Rectangle's style. Note that fill-opacity is not defined here. This allows class attributes to be overridden.

2

JavaScript calls for onmouseover and onmouseout.