Using Javascript to control an SVG

Like HTML, SVGs are represented using the Document Object Model (DOM) and so can be manipulated with Javascript relatively easily.

First create your SVG. Give the element you want to control an id so it can be easily selected.

<svg version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     width="400" height="300">
  <style>
    circle {
      fill-opacity: 0.5;
      stroke-width: 4;
      fill: #3080d0;
      stroke: #3080d0;
    }
  </style>
  <circle id="my-circle" cx="100" cy="100" r="50" />
</svg>

Then add the SVG into your HTML document with the object tag and give that an ID.

<object id="circle-svg" width="400" height="300" type="image/svg+xml" data="moving_circle.svg"></object>

Javascript

You can then select the SVG element by its ID:

var svg = document.getElementById("circle-svg"); 

Then select the SVG document:

var svgDoc = svg.contentDocument;

Then select elements within the document:

var circle = svgDoc.getElementById("my-circle");

You can manipulate an element's attributes with setAttributeNS():

circle.setAttributeNS(null, "cx" 200);

Example

You can see an example at http://www.petercollingridge.appspot.com/svg-and-js

It uses the HTML5 slider element (which only works properly in Chrome or Safari) to control the position of the circle. The files used can be downloaded below (the HTML file is a text file - you just need to change the extension). Note that the Javascript may not run if you open the HTML on your computer, but will work when run on a server.

AttachmentSize
moving_circle.svg361 bytes
svg-interaction.js.txt268 bytes
svg-and-js.txt662 bytes