I have a HTML5 page with a SVG element in it. I would like to load a SVG file, extract some elements from it and dispose them one by one with a script.
I used jQuery
Given an SVG file 'image.svg' containing
and a file 'index.html' containing
then if file 'script.js' contains
$(document).ready(function() {
var image = SVG('svgimage');
$.get('image.svg', function(contents) {
var $tmp = $('svg', contents);
image.svg($tmp.html());
}, 'xml');
$('#svgimage').hover(
function() {
image.select('rect').fill('blue');
},
function() {
image.select('rect').fill('yellow');
}
);
});
then the SVG image will display and moving the mouse pointer in and out of the browser window will change the color of the rectangle from yellow to blue.
You should now be able to substitute any SVG image file and define any number of functions to manipulate the image using the SVG.js library. The important thing to realize is that calls to SVG.js methods will not succeed if they take place before the $(document).ready function has returned.
For bonus points, I also found copying the values of the 'viewBox', 'width' and 'height' attributes by adding the following lines after the declaration of '$tmp' to work best for successfully displaying the contents of arbitrary SVG files:
image.attr('viewBox', $tmp.attr('viewBox'));
image.attr('width', $tmp.attr('width'));
image.attr('height', $tmp.attr('height'));