0

I'm dynamically creating a series of circles using SVG.
The code creates a valid DOM, as you can check in the developer window of the browser.

The circles won't show though...
Only after changing something in the svg code in the DOM in the developer window, the circle(s) show.

Here's my code. I hope it's self-explanatory.
I distilled my original code down to the essence.

(No jQuery solutions please.)

HTML:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>svg</title>
    </head>
    <body>
        <div id="test"></div>
        <script>
TOOLTIPS = [
  { "x": 100, "y": 100 },
  { "x": 200, "y": 200 }
];

(function () {
var obj = document.createElement('object');
obj.type = 'image/svg+xml';
obj.data = 'test.svg';
obj.onload = function () {
    TOOLTIPS.forEach(function (index) {
        var svgDoc = document.getElementsByTagName('object')[0].contentDocument;
        var svgRoot = svgDoc.documentElement;
        var group = svgRoot.getElementById('layer1');
        var use = svgDoc.createElementNS('http://www.w3.org/2000/svg', 'use');

        use.setAttribute('xlink:href', '#blue');
        use.setAttribute('transform', 'translate(' + index.x + ' ' + index.y + ')');

        group.appendChild(use);
    });
};
document.getElementById('test').appendChild(obj);
})();
    </script>
</body>

SVG ('test.svg'):

<svg id="svgBody" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1366 768">
  <defs>
    <circle id="blue" style="fill: #00f" cx="12.5" cy="12.5" r="8" />
  </defs>
  <g id="layer1"></g>
</svg>
  • I'm curious why you are using an `` here. Why not just do it inline in you main HTML file? – Paul LeBeau Jul 24 '18 at 09:57
  • 2
    Use setAttributeNS to create the xlink:href element and make sure you specify the xlink namespace as the first argument. – Robert Longson Jul 24 '18 at 09:59
  • 1
    `use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#blue');` – Paul LeBeau Jul 24 '18 at 10:11
  • 1
    Also be aware that, on Chrome, `contentDocument` won't work (it will always be null) if you are loading your HTML test file from you local file system (ie. `file://`). See: https://stackoverflow.com/questions/5333878/google-chrome-wont-accept-contentdocument-or-contentwindow If that is the case for you, then run a local web server, or use Firefox to test. – Paul LeBeau Jul 24 '18 at 10:13
  • THANKS! I was under the impression I did not need `setAttributeNS` in this case, but obviously I was mistaken. @Paul LeBeau, thanks for the heads-up about `contentDocument`. –  Jul 24 '18 at 11:17

0 Answers0