[Warning] Warning

This section not yet updated for Inkscape v0.92.

Adding JavaScript

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 (Object icon Object Properties... (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.

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. 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"?>
  <a xlink:href="http://www.w3.org/"
     style="fill-opacity:0.75">     1
     style="fill:#0000ff;stroke:#000000"     2
     onmouseover="setAttribute('fill-opacity','1.0')"     3
       id="desc3364">A clickable square to test simple JavaScript.</desc>
       id="title3362">Click square to go to http://www.w3.org.</title>



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