0

I loaded an svg file with and when trying to modify a style attribute with this:

$("object").contents().find('#path5431').css('fill', 'red');

I get nothing. The code is run after the svg is loaded. Any tips?

Thanks.

Edit:

<body>
     <object data='image.svg'></object>
</body>
Gabriel
  • 5,453
  • 14
  • 63
  • 92
  • 1
    I think we'd need to see some HTML but if it's an inline svg `contents()` isn't needed. Otherwise (embedded) you'll have much trouble accessing it. – Shikkediel Apr 03 '15 at 14:02
  • Hi Shik. Added how i embedded the svg file. – Gabriel Apr 03 '15 at 14:15
  • Check out this jQuery plugin - http://keith-wood.name/svg.html. From my understanding, jQuery can't interact well with svg naively. – Howard Renollet Apr 03 '15 at 14:20
  • Yeah, I've found it troublesome to use any JavaScript on an svg like that. When it's inline, with some jQuery and vanilla JS to fill in the gaps pretty much any manipulation is possible though. If it's a large file, you could try and put it on the server as a `.txt` and use `.load()` to dynamically add it - if it would otherwise crowd the page source. I have yet to try this myself though. – Shikkediel Apr 03 '15 at 14:25

1 Answers1

1

If the SVG is inline (embedded) into the html, editing it via CSS/Javascript is relatively simple.

However, when loaded from an external file, manipulation of the SVG structure is extremely difficult to say the least.

You might want to look into using something like an AJAX load to embed the SVG into the html, then manipulate ...

There are several issues with this approach (see How do I dynamically insert an SVG image into HTML?).

However, I've successfully used SVGInjector (see https://github.com/iconic/SVGInjector) to do things like:

<img id="image-one" class="inject-me" data-src="image-one.svg">
<img id="image-two" class="inject-me" data-src="image-two.svg">
// Elements to inject
var mySVGsToInject = document.querySelectorAll('img.inject-me');

// Options
var injectorOptions = {
  evalScripts: 'once',
  pngFallback: 'assets/png',
  each: function (svg) {
    // Callback after each SVG is injected
    console.log('SVG injected: ' + svg.getAttribute('id'));
  }
};

// Trigger the injection
SVGInjector(mySVGsToInject, injectorOptions, function (totalSVGsInjected) {
  // Callback after all SVGs are injected
  console.log('We injected ' + totalSVGsInjected + ' SVG(s)!');
});

I also ran into these articles recently ...

Community
  • 1
  • 1
rfornal
  • 5,072
  • 5
  • 30
  • 42
  • I would just add that the svg injector library is now included in iconic.js so you can just use IconicJS().inject(mySVGsToInject, injectorOptions) to accomplish the same result. – Marko Apr 05 '16 at 20:29