1

I have made some paths in Illustrator and exported this as .svg. Now I want to animate these paths with css and javascript. I have already found a good fiddle that is working when I load the svg inline in HTML5. Because there are many paths(about 500) I want to embed this in HTML5. My problem: I can't access the svg file while it's embedded. How can I access all my paths/lines/polygons while the svg is embedded?

HTML:

<embed src="pano_botanique.svg" width="100%" height="100%" ; type="image/svg+xml"      id='svgsource' />

JS:

$(document).ready(function () {

    var svgs = document.getElementsByTagName('svg');

    function selfdraw() {
        for (var i = 0; i < svgs.length; i++) {
            svgs[i].classList.add('draw');
        }
    }
});

CSS:

svg * {
    fill: none;
    stroke: none;
}

.draw * {
    stroke: #3675D8;
    stroke-width: 0.5px;
    -webkit-animation: self-draw 30s ease-in;
    -webkit-animation-fill-mode: backwards;
}

@-webkit-keyframes self-draw {
    0% {
    stroke-dasharray: 0 100%
    }
    40% {
    stroke-dasharray: 100% 0%
    } 
}

EDIT:

var svgs = document.getElementById('svgsource').contentDocument();
svgs.addEventListener('load', function () {
    var svg = svgs.contentDocument();

function selfdraw() {
    for (var i = 0; i < svgs.length; i++) {
        svgs[i].classList.add('draw');
    }
}
});

This should work but doesn't :(

Nick
  • 71
  • 6

1 Answers1

0

You can put the stylesheet in a <style> element inside the svg file.

Note that by using <embed> the svg nodes are in a different document. That means that for getElementsByTagName(...) to work you need to call it on the svg document, not on the main document.

But simply replacing document with e.g document.getElementById('svgsource').getSVGDocument() isn't guaranteed to work unless you wait for the svg document to finish loading (read: you can't do this from $(document).ready, see this answer for more details.

Also see How to access the content of the "embed" tag in HTML.

Community
  • 1
  • 1
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139