6

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 onClick a function external to the svg to do some stuff (for instance, retrieving by ajax some people data related to the area selected and show them outside the svg in the html page).

What I'm not able to do is to trigger a function defined outside the svg from an element in the svg.

I can do this if i add the svg inline, but I need to use the embed tag to make it work with ie Adobe plugin. Any suggestion? Thanks in advance.

Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139
Alex
  • 191
  • 2
  • 10
  • You can't have JavaScript executed from SVG, if it is embedded via ``, `` or alike. – Sirko May 07 '12 at 16:02
  • …but jQuery wasn't made for SVG handling. – feeela May 07 '12 at 16:06
  • Possibly what you want to look into is a library such as http://raphaeljs.com/ – qw3n May 07 '12 at 16:08
  • Unfortunatly the svg is too complex and I have problems processing it with raphael. There is no workaround to achieve the goal? – Alex May 07 '12 at 16:29
  • you can work with the DOM directly or use something like d3.js. Raphael should also work if you load it corectly. – mihai May 08 '12 at 21:26

1 Answers1

11

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.";
}
Erik Dahlström
  • 59,452
  • 12
  • 120
  • 139