Skip to content Skip to sidebar Skip to footer

How To Call A Function In The Parent Html Document From An Embedded Svg

I'm quite new to svg and I have to perform a task with it, but I'm having lots of troubles. I have an svg (a map for instance) with areas defined by paths. My goal is to trigger on

Solution 1:

See this example.

The code inside the svg looks like this:

    document.getElementById("svgroot").addEventListener("click", 
                                                        sendClickToParentDocument,
                                                        false);

    function sendClickToParentDocument(evt)
    {
        // SVGElementInstance objects aren't normal DOM nodes, 
        // so fetch the corresponding 'use' element instead
        var target = evt.target;
        if(target.correspondingUseElement)
            target = target.correspondingUseElement;

        // call a method in the parent document if it exists
        if (window.parent.svgElementClicked)
            window.parent.svgElementClicked(target);
        else
            alert("You clicked '" + target.id + "' which is a " + target.nodeName + " element");
    }

And in the parent document you have a script with a function you want to call, e.g:

function svgElementClicked(theElement)
{
    var s = document.getElementById("status");
    s.textContent = "A <" + theElement.nodeName + 
        "> element with id '" + theElement.id + 
        "' was clicked inside the <" + 
        theElement.ownerDocument.defaultView.frameElement.nodeName.toLowerCase() + 
        "> element.";
}

Post a Comment for "How To Call A Function In The Parent Html Document From An Embedded Svg"