0

I'm building a site that has an embedded SVG logo at the top. It has a nifty animation as it draws itself. Though in tests, the animation is distracting as it animates on every page. I added a class to the SVG where if it has

 <svg class="showAnimation">

it animates, and if it doesn't have that class, it doesn't animate. Or even if the showAnimation class is on any parent, that will work. But doing

<embed src="/media/logo.svg" class="showAnimation">

doesn't work as I guess classes in the HTML aren't propagated down. I don't want to inline the SVG file and have the whole thing re-loaded on every page.

The long story short is: I'm looking for an efficient way to add/remove classes to an embedded SVG from the HTML/CSS/Javascript side before the SVG is shown. Inline is inefficient as it can't be cached, making two separate SVG files with only one word different is inefficient.

Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35

1 Answers1

0

You could get the elements inside an embed element through getSVGDocument().

var el = document.getElementById("embed's-id");
el.addEventListener("load", function() {
  var svg = el.getSVGDocument().getElementById("your-svg's-id");
  svg.setAttribute('class', 'showAnimation');
});

If the load event doesn't trigger, try doing it this way.

function checkIfLoaded() {
  var svg = document.getElementById("embed's-id").getSVGDocument();
  if (svg == null) {
    setTimeout(checkIfLoaded, 100);
  } else {
    svg.setAttribute('class', 'showAnimation');
  }
}

checkIfLoaded();
Weafs.py
  • 22,731
  • 9
  • 56
  • 78
  • Any idea why "load" may never trigger? Nothing in that function is run. There are no javascript errors, I do var embedLogo = document.getElementById("embedLogo"); embedLogo.addEventListener("load", function() { alert("loaded");}); and never get an alert. From the javascript console I can check that embedLogo is defined properly though. – Dan Goodspeed Dec 24 '14 at 00:45
  • @DanGoodspeed - Strange! It should work. Maybe try doing it [this way](http://jsfiddle.net/chipChocolate/59q9nfxz/1/). – Weafs.py Dec 24 '14 at 01:12
  • Hmm, this is unrelated to my last problem… but it looks like classList doesn't work on an SVGDocument. document.getElementById("embedLogo").classList works fine. document.getElementById("embedLogo").getSVGDocument().classList returns undefined. – Dan Goodspeed Dec 24 '14 at 01:50
  • @DanGoodspeed - Opps my bad! You have to do `svg.setAttribute('class', 'showAnimation')` instead. – Weafs.py Dec 24 '14 at 01:52
  • .setAttribute is also undefined for the SVGDocument (again working only on the HTML element). – Dan Goodspeed Dec 24 '14 at 02:13
  • `getSVGDocument` may not work in all situations. Try using the `getSubDocument()` function from the script linked to in this answer: http://stackoverflow.com/questions/8496241/how-to-access-the-content-of-the-embed-tag-in-html/8496279#8496279 – Paul LeBeau Dec 24 '14 at 02:52