Simple SVG manipulation with jQuery
Okay, so I wanted to do something ‘simple’. I just wanted to load in an SVG document into a webpage, and then add bits to it.
Loading the SVG is easy. To make things even easier, with modern browsers I can just drop the SVG code in-line into my document and it works. For this project I don’t care too much about it not rendering on legacy browsers; The UI will fall-back gracefully without the SVG there.
So first, I’m going to start with some boilerplate code. I’m not claiming this is the best in the universe, but it’s basically “load jquery. chuck some SVG on the page”:
<head> <title>Simple SVG example</title> </head> <body> <div><svg xmlns="http://www.w3.org/2000/svg" version="1.1" id="mySVG"> <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="aquamarine"/> </svg></div> </body></html>
Great. It draws a circle.
Now I’ve given the svg element an id of mySVG, so using jQuery to add extra elements to the drawing is easy. The only problem is that the elements it has have to be in the ”http://www.w3.org/2000/svg” namespace, and as far as I’m aware, jQuery doesn’t let you add a namespace when creating a new element.
It’s pretty easy to work around. I just use document.createElementNS() to make the element with the correct namespace, and then be slack and use jQuery to do the rest.
He’s some code I’m using to do just that. It’s a bit more abstracted than for a simple example, mainly because I’m going to be adding more than one or two items: