Over the last couple of months I’ve found myself more and more using Javascript and JQuery for front end interactions and little shenanigans. I’m enjoying it! It’s nice to be actually starting to understand how JS can be both beneficial and implemented in clean ways on sites and one of the things I’ve been playing with recently has been how it can be used to manipulate SVG graphics files, specifically ones created in Illustrator.

Now, there’s a reason for this related to a potential project I’ve got coming up, but loading SVG files into a html page and manipulating them with Javascript is actually quite cool! A key thing to understand is that SVG files are formatted with XML, meaning you can actually grab elements via the DOM in Javascript and play with their position, colour, etc. VS Code has been helpful here as loading SVG into that breaks open the XML and lets you see how the file is structured. Illustrator as well has been invaluable here, particularly with how it saves layer names as ID attributes on the various elements within the SVG file.

I’ve knocked up a wee demo which you can find on GitHub here. I won’t go into too much detail, but it’s a quick Node app which you’ll need to install with:

npm install

Once you’ve got it all up and running you can run the Express server with:

node app.js

and point your browser at http://127.0.0.1:3000/. You’ll see the SVG rendered on the screen. Take a look at the Javascript files to see what then happens. Basically, some of the rectangles are recoloured (rectsPaint.js) and have some EventListener rules added to dynamically change the fill colour on click or mouseover/out. To help myself with this I’m writing the structure of the SVG file into an object which I can call on as I need (initRects.js).

As I say, this is very much just a little experiment. There are a few JS libraries set up specifically to handle SVG files which I’m going to be looking at over the next week but, for now, check out the repo and let me know your thoughts!