4

I'm wondering if there's a way in jQuery to grab some SVG data included in a div on a page and place that data into a CSS background-image url? I'm trying to do this instead of loading an external SVG file, as I'd like to have a completely self-contained HTML file. I'm trying to do something like this:

var svgData = $("#div-containing-svg").html()
$("other-div").css({backgroundImage:svgData});

Is this possible? And further, would it work across browsers?

itsmikem
  • 2,118
  • 2
  • 26
  • 31
  • I've seen this done as a canvas - how flexible are you? – Mike Robinson Dec 18 '12 at 17:20
  • It can be done as a data URI, e.g. `background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxu [and so on]");` so if you can massage your data into that form, somehow...? I found http://jsfiddle.net/estelle/SJjJb/ which uses straight SVG but it only appears to be webkit-friendly. – Olly Hodgson Dec 18 '12 at 17:22

2 Answers2

2

You should do something like:

var image = $('#svg-container').html();
$('#elem').css('background-image', 'data:image/svg+xml;utf8,' + image);

Is it cross-browser? Here you can see a compatibility matrix: http://caniuse.com/svg-css

  • The SVG content should be url escaped
Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
0

A working example of the answer by @minko-geschev:

https://stackoverflow.com/a/21626701/960592

The provided answer uses base64 encoding, instead of escaping.

Ideogram
  • 1,265
  • 12
  • 21