Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

Up and Running with SVG

An SVG primer for everyone. Created by Mijingo.

Manipulating SVG with JavaScript

Just like we can do style overrides with CSS, we can also manipulate our SVG image with JavaScript. Manipulating SVG with JavaScript isn’t different than any other DOM element. We can use JavaScript, jQuery, or whatever other flavor of the month we’d like.

Here’s a really simple example of changing the fill attribute of the rect with the id of “inner.”

function blackOutCenter() {
 document.getElementById("inner").setAttribute("fill", "#333");
}

Wired to a button, like in the working example, this uses the setAttribute method to update the fill attribute to #333.

We can also read the current attributes and then make decisions based on what we get back.

function getFillColor() {
    svgRect = document.getElementById("inner");
    var fillColor = svgRect.getAttribute("fill");
}

See Intro to SVG: Example 13

This is basic stuff if you’re familiar with using JavaScript to affect DOM elements.

Using a JavaScript Library

There are also libraries we can use, which make it really simple to create and manipulate SVG. Here are some popular libraries you should consider:

Ready to learn more?

Get the Full Video Course