Using script code in my SVG file

Article ID: 2263
Last updated: 29 May, 2018
Article ID: 2263
Last updated: 29 May, 2018
Revision: 3
Views: 550
Posted: 23 Jun, 2010
by Dean J.
Updated: 29 May, 2018
by Gargani A.

Question

How can I use script code in my SVG file?

Answer

The SVG specification describes how to plug script code into an SVG document. This is explained in detail in this section:

   SVG Specification - Chapter 18 - Scripting
      http://www.w3.org/TR/SVG11/script.html

The key to the scripting capabilities is to add a <script> section to the <svg> tag to define the ECMAScript code, with visibility for the whole document. The script functions defined there can be invoked from the onclick, onload, and other such attributes set on the elements of the SVG document.

The attached sample performs these actions on an SVG file generated by JViews: the SVGDocumentBuilder class is responsible for building the DOM structure of the SVG document. In particular, the sample overrides the translate and afterBuildingDocument methods to add the scripting capabilities to the final document.

To test the sample, compile the attached class with
 
   javac ScriptInSVGOutput.java
 
and run it with
 
   java ScriptInSVGOutput
 
A window shows two rectangles in the JViews manager and an output.svg file is produced. Open this file in an SVG-capable browser (such as IE with SVG plug-in) and the same two rectangles will be visible in the browser. Clicking the rectangles in the browser causes a message window to be displayed. This window is invoked from the embedded script code.

Note: In order to run this sample in JViews 8.7 or newer, you must call the ilog.views.util.IlvProductUtil.DeploymentLicenceRequired method with the appropriate argument. 

This article was:   Helpful | Not helpful
Report an issue
Article ID: 2263
Last updated: 29 May, 2018
Revision: 3
Views: 550
Posted: 23 Jun, 2010 by Dean J.
Updated: 29 May, 2018 by Gargani A.
Attached files


Others in this category