views:

1331

answers:

3

I need to edit (using javascript) an SVG document embedded in an html page.

When the SVG is loaded, I can access the dom of the SVG and its elements. But I am not able to know if the SVG dom is ready or not, so I cant' perform default actions on the SVG when the html page is loaded.

To access the SVG dom, I use this code:

var svg = document.getElementById("chart").getSVGDocument();

where "chart" is the id of the embed element.

If I try to access the SVG when the html document is ready, in this way:

jQuery(document).ready( function() {
var svg = document.getElementById("chart").getSVGDocument();
...

svg is always null. I just need to know when it is not null, so I can start manipulate it. Do you know if there is a way to do it?

A: 

You can assign an onload event handler to an element within your SVG document and have it call a javascript function in the html page. onload maps to SVGLoad.

http://www.w3.org/TR/SVG11/interact.html#LoadEvent

The event is triggered at the point at which the user agent has fully parsed the element and its descendants and is ready to act appropriately upon that element

Mocky
No, I can't edit the SVG document. I just can manipulate it when is in the web page.
alexmeia
A: 

You could try polling every so often.

function checkReady() {
    var svg = document.getElementById("chart").getSVGDocument();
    if (svg == null) {
        setTimeout("checkReady()", 300);
    } else {
        ...
    }
}
Mocky
Yes, it works. Didn't think about the timeout solution... Thanks man.
alexmeia
Polling is not a good way of doing this. Use a 'load' event listener instead.
Erik Dahlström
A: 

On your embedding element (e.g 'embed', 'object', 'iframe') in the main document add an onload attribute which calls your function, or add the event listener in script, e.g embeddingElm.addEventListener('load', callbackFunction, false). Another option might be to listen for DOMContentLoaded, depends on what you want it for.

You can also add a load listener on the main document. jQuery(document).ready doesn't mean that all resources are loaded, just that the document itself has a DOM that is ready for action. However note that if you listen for load on the entire document your callback function won't be called until all resources in that document are loaded, css, javascript etc.

If you use inline svg, then jQuery(document).ready will work just fine however.

On a further note you might want to consider using embeddingElm.contentDocument (if available) instead of embeddingElm.getSVGDocument().

Erik Dahlström