Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading SVG into SVGWeb dynamically with JQuery

Tags:

jquery

svg

I am trying to dynamically display some SVG content. This content is stored as a string in my data source. An example string would look like the following:

<svg width="200" height="200" style="background-color:#D2B48C; margin-bottom:5px;" id="embeddedSVG">
<g id="myGroup" fill="blue" style="font-size:18px; text-anchor:middle; font-family: serif;">
<circle id="myCircle" cx="100" cy="75" r="50" stroke="firebrick" stroke-width="3" />
<text x="100" y="155">Hello World</text><text x="100" y="175">From Embedded SVG!</text>
</g></svg>

To accomodate for IE, I'm using SvgWeb. My problem is, to display svg content, I need to wrap it in a <script type="image/svg+xml"></script> tag combo. My challenge is, the svg is being pulled back asynchronously via JQuery. And, to my knowledge, I can't dynamically write a 'script' tag from JavaScript.

How do I take the SVG content that is retrieved with JQuery and dynamically display it?

like image 509
user462166 Avatar asked Oct 07 '10 15:10

user462166


1 Answers

Found a partial answer here and reproduced below. Note, that this approach forces you to build the root <svg> tags and attributes yourself in javascript instead of just loading the whole svg document that you have in your question's example.

Dynamically creating an SVG Root element is similar for direct embedding into a web page. You don't have to create a SCRIPT tag like you would if you were direct embedding the SVG on page load:

<script type="image/svg+xml">
  <svg>
    ...
  </svg>
</script>

Instead, you follow a process similar to the above:

// create SVG root element
var svg = document.createElementNS(svgns, 'svg'); // don't need to pass in 'true'
svg.setAttribute('width', '300');
svg.setAttribute('height', '300');

// create an example circle and append it to SVG root element
var circle = document.createElementNS(svgns, 'circle');
svg.appendChild(circle);

Must use a callback to know when SVG is appended to page (this is slight divergence from standard). The following are supported ways to do this:

svg.addEventListener('SVGLoad', function() {
  svg = this; // this will correctly refer to your SVG root
  alert('loaded!');
}, false);
// also supported:
svg.onsvgload = function() {
  alert('loaded!');
}

Now append the SVG root to our document

svgweb.appendChild(svg, document.body); // note that we call svgweb.appendChild

Note in the above code that we have to use an event listener to know when the SVG root is finished loading into the page; this is a slight divergence from the standard necessary for SVG Web's magic.

The parent that you attach either your SVG root must already be attached to the real DOM on your page (i.e. it can't be disconnected from the page).

like image 105
awesomo Avatar answered Oct 07 '22 21:10

awesomo