SVG Scripting

Jakob Jenkov
Last update: 2014-06-15

It is possible to script SVG using JavaScript. Via scripting you can modify the SVG elements, animate them, or listen for mouse events on the shapes.

When SVG is embedded in an HTML page, you can work with SVG elements in JavaScript just as if they were HTML elements. The JavaScript looks the same.

This text shows you examples of how to work with SVG elements via JavaScript, but it does not explain JavaScript itself. To understand the examples in this text you need to have a reasonable understanding of JavaScript already.

SVG Scripting Example

Here is a simple SVG scripting example which changes the dimensions of an SVG rectangle when a button is clicked.

<svg width="500" height="100">
    <rect id="rect1" x="10" y="10" width="50" height="80"
          style="stroke:#000000; fill:none;"/>
</svg>
<input id="button1" type="button" value="Change Dimensions"
            onclick="changeDimensions()"/>

<script>
    function changeDimensions() {
        document.getElementById("rect1").setAttribute("width", "100");
    }
</script>

Try clicking the button to see what happens.

Getting a Reference to an SVG Element by ID

You can obtain a reference to an SVG shape using the document.getElementById() function. Here is an example:

var svgElement = document.getElementById("rect1");

This example gets a reference to the SVG element with the ID rect1 (the ID is specified inside the SVG element's id attribute).

Changing Attribute Values

Once you have obtained a reference to the SVG element you can change its attributes using the setAttribute() function. Here is an example:

var svgElement = document.getElementById("rect1");

svgElement.setAttribute("width", "100");

This example sets the selected SVG element's width attribute. You can set any other attribute using the setAttribute() function, including the style attribute.

You can also get the value of an attribute using the getAttribute() function. Here is an example:

var svgElement = document.getElementById("rect1");

var width = svgElement.getAttribute("width");

Changing CSS Properties

You can change the CSS properties of an SVG element by referencing the given CSS property via the element's style property. Here is an example that sets the stroke CSS property:

var svgElement = document.getElementById("rect1");

svgElement.style.stroke = "#ff0000";

You can set any other CSS property this way too. Just put its name after the svgElement.style. part of the second line above, and set is value to something.

You can also read the value of a CSS property via the style property. Here is an example:

var svgElement = document.getElementById("rect1");

var stroke = svgElement.style.stroke;

This example reads the value of the stroke CSS property.

CSS property names that contain a dash inside the name, like stroke-width, needs to be referenced via the [''] construct. That is done because property names with a dash inside are not valid in JavaScript. Thus you cannot write

element.style.stroke-width

Instead you have to write

element.style['stroke-width']

That way you can also reference CSS properties with a dash in their name.

Event Listeners

You can add event listeners to an SVG shape directly in the SVG if you want. You do so just like you would with an HTML element. Here is an example that adds an onmouseover and onmouseout event listener:

<rect x="10" y="10" width="100" height="75"
      style="stroke: #000000; fill: #eeeeee;"
      onmouseover="this.style.stroke = '#ff0000'; this.style['stroke-width'] = 5;"
       onmouseout="this.style.stroke = '#000000'; this.style['stroke-width'] = 1;"
        />    

This example changes stroke color and stroke width when the mouse hovers over the rectangle, and resets the stroke color and stroke width when the mouse leaves the rectangle. You can try the example live below. Try moving the mouse over the shape, and out again, to see the effect of the event listeners.

You can also attach an event listener to an SVG element using the addEventListener() function. Here is an example:

var svgElement = document.getElementById("rect1");
svgElement.addEventListener("mouseover", mouseOver);


function mouseOver() {
    alert("event fired!");
}

This example adds an event listener function called mouseOver to the mouseover event. That means, that whenever the user hovers the mouse over the SVG element, the event listener function is called.

Animating SVG Shapes

In order to animate an SVG shape you need to call a JavaScript function repeatedly. The function changes the position or dimensions of a shape. When the function is called repeatedly and with very short intervals in between, the shape will have its position or dimensions updated with very short intervals too, which makes the shape appear animated.

Here is an SVG scripting animation example. The code to create it is shown below the example. Click the two buttons below the SVG image to start and stop the animation.


Here is the code needed to generate the above animation:

<svg width="500" height="100">
    <circle id="circle1" cx="20" cy="20" r="10"
            style="stroke: none; fill: #ff0000;"/>
</svg>

<script>
    var timerFunction = null;

    function startAnimation() {
        if(timerFunction == null) {
            timerFunction = setInterval(animate, 20);
        }
    }

    function stopAnimation() {
        if(timerFunction != null){
            clearInterval(timerFunction);
            timerFunction = null;
        }
    }

    function animate() {
        var circle = document.getElementById("circle1");
        var x = circle.getAttribute("cx");
        var newX = 2 + parseInt(x);
        if(newX > 500) {
            newX = 20;
        }
        circle.setAttribute("cx", newX);
    }
</script>
<br/>
<input type="button" value="Start Animation" onclick="startAnimation();">
<input type="button" value="Stop Animation" onclick="stopAnimation();">
    

The two HTML buttons have an onclick listener attached to them. These listeners call the startAnimation() and stopAnimation() functions which start and stop the animation. The animation is started by setting up a timer which calls the animate() function every 20 milliseconds. The animation is stopped by clearing this timer function again.

The animation is performed inside the animate() function. First the function gets a reference to the <circle> element in the SVG image via the document.getElementById() function. Then the cx attribute of the circle is read and converted to a number. Then 2 is added to the cx value. If the new x value is larger than 500, then it is reset to 20. Finally the new x value is put back into the cx attribute of the <circle> element. The circle is thus moved to a new x-position.

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next