Bram
Bram

Reputation: 8313

Routing onclick event from embedded SVG to higher level

I have an HTML file that embeds two different SVG files, like so:

<html>
  <body>
    <object id="svg0" data="histograms.svg" type="image/svg+xml"></object>
    <object id="svg1" data="test.svg" type="image/svg+xml"></object>
  </body>
</html>

Both SVG files are interactive, by adding a javascript function that is triggered by onclick, like such:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:ns1="http://www.w3.org/1999/xlink" height="172pt" version="1.1" viewBox="0 0 1209 172" width="1209pt">
 <script type="text/ecmascript">
                function choose(obj) {
                  var values = [0.08,0.77];
                  var names = [ "hist_1", "hist_2", "hist_3", "hist_4", "hist_5", "hist_6", "hist_7", "hist_8", "hist_9", "hist_10", "hist_11" ];
                  for ( var i=0; i&lt;names.length; i++) {
                    var o = document.getElementById( names[i] );
                    o.style['opacity'] = values[0];
                  }
                  obj.style['opacity'] = values[1];
                }
  </script>
  ...
 <g id="figure_1">
  <g id="patch_1">
   <path d=" M0 172.8 L1209.6 172.8 L1209.6 0 L0 0 z " style="fill:#ffffff;" />
  </g>
  <g id="axes_1">
   <g cursor="pointer" id="hist_1" onclick="choose(this)">
    <path d=" M20.835 70.52 L189.696 70.52 L189.696 12.96 L20.835 12.96 z " style="fill:#ffe6cc;" />
   </g>
...

How can I have a click in one SVG file trigger javascript in the other SVG file? (Possibly via top level .html file as intermediate, if necessary?)

Upvotes: 3

Views: 68

Answers (1)

Robert Longson
Robert Longson

Reputation: 124289

If you're writing code in test.svg then top gets you the containiner, so

var svg0 = top.document.getElementById("svg0");

would get you the object element from the container document.

Then

obj0Document = svg0.contentDocument;
if (obj0Document && obj0Document.defaultView)
  obj0Window = obj0Document.defaultView;
else if (svg0.window)
  obj0Window  = svg0.window;

gets you the content's document and window.

accessing the SVG document's "window" allows you to access variables and functions defined in scripts in the SVG document.

e.g. obj0Window.choose(something)

Everything must have the same domain for this to work.

Upvotes: 2

Related Questions