Getting Starting with SVG and JavaScript

I’ve started using SVG in a web application.  I looked into some SVG libraries, but decided it was overkill for what I needed. So I took a deeper look.

Lets start by dumping an inline SVG element in a page.  Boring, but it renders great in the modern browser.

 

The above example obscures an interesting thing.  The SVG elements have a different namespace than your normal HTML elements.  This becomes very important once we start using JavaScript to do our magic.

Creating & Modifying SVG with JavaScript

Using jQuery

It’s pretty safe to say jQuery is used often in web projects, so why not just use it to create your SVG.

Adding an inline SVG with jQuery does work great!

View Demo on jsFiddle

However I start to run into problems when updating the SVG after it is created.  So lets look at what happens when I try to add the rectangle after the SVG element is created.

View Demo on jsFiddle

After running the demo you’ll see an empty page.  If you look at the elements with the developer tools, you’ll see the entire SVG.  It just doesn’t render in the page.  The issue is jQuery doesn’t use the proper namespace when creating the SVG elements.

So I’m going to put aside jQuery for now.  If you are dead set on using jQuery with SVG, grab this jQuery SVG plugin.

Doing it with vanilla JavaScript

Because the namespace is the key problem in the above example, I’ll use the document.createElementNS() method to create the SVG elements.  You need to use this namespace for SVG:

  • http://www.w3.org/2000/svg

View Demo on jsFiddle

The end result is SVG I can update any time in the modern browser.

2 thoughts on “Getting Starting with SVG and JavaScript

  1. Pingback: SVG and Handlebars JS Templates | No Circle No! : Blog

  2. Pingback: SVG with Backbone JS | No Circle No! : Blog

Comments are closed.