Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to navigate SVG object's elements from enclosing HTML?

Tags:

svg

I'm loading an SVG through an object tag and need to access SVG's elements (to manipulate them). How can I do that?

Here're partial solutions I'm aware of:

  1. Use SVG params where you set params for the object tag and parameterize attributes of the SVG elements. This works great for things like rect, but not for g (group) that I need to move (that takes a "transform" that can't be parameterized, looks like).

  2. I've seen suggestions to use contentDocument or getSVGDocument() on the object element that you get through getElementById("yoursvgid"). Unfortunately, neither is working - and yes, I'm calling these after the SVG is loaded.

I can't believe there is no simple/reliable way to access SVG elements from within HTML (searched here/web) - would really appreciate help on this!

Alternatively, if there is some way to call a function defined inside SVG from within HTML (or vice versa), that'd do it too. In general, any way to communicate between SVG and HTML.

like image 689
Sekhar Avatar asked Feb 06 '11 04:02

Sekhar


1 Answers

Here's a technique I have used successfully, mentioned in the (very good) O'Reilly "SVG Essentials" book:

  1. Add JavaScript code to your SVG document itself and handle the load event on the root svg element.

    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" onload="init(evt)">
    <script type="text/ecmascript" xlink:href="svgScript.js" />
    
  2. In this svgScript.js load event handler, write out whatever you need to expose to the HTML-side script through the built-in parent variable.

    function init(evt) {
        svgDocument = evt.target.ownerDocument;
        parent.theSvgDocument = svgDocument;
    }
    
  3. Back in your HTML-side script, you can now directly access and use this reference.

    var svgDocument = theSvgDocument;
    

In this example we expose the SVG Document object but you could pass on any object or a function. In my project I actually exposed some kind of controller object reference so that my SVG-side script contains all the logic for manipulating the SVG document, and the HTML-side script merely grabs this controller object and calls public methods on it.

like image 172
Clafou Avatar answered Sep 18 '22 23:09

Clafou