How to call a function in parent html document from embedded svg

I am new to svg and I have to complete the task with it, but I have a lot of problems.

I have svg (e.g. map) with areas defined by paths.

My goal is to call an onClick function external to svg to do some things (e.g. ajax fetching some data from a selected area by ajax and showing it outside svg on the html page).

What I cannot do is to call a function defined outside of svg from an element in svg.

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

+6
source share
1 answer

See this example .

The code inside 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 the function you want to call, for example:

 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."; } 
+10
source

Source: https://habr.com/ru/post/915102/


All Articles