Alex Rivera | Logout

Add click event on elements of an embedded SVG in javascript

Asked 2012-03-30T14:48:01.897
17

I got this SVG image from Wikipedia and embedded it into a website using this code:

<embed src="circle1.svg" type="image/svg+xml"/>

If you run this, you can inspect the element and see the source code. All countries in the image are separate elements. If I click on a country, I want to alert the id of that country, since every country has an id of two letters in the SVG. Does anyone know a way to do this? Would it be easier if I place it into a element?

Edit
Report

1 Answer

5

Update July 2016

It is possible to respond to events from embed elements now, under the condition that you embed something from the same domain. I have created a quick demonstration of this as a JSFiddle. The most important part is that it is possible to access the embedded document through embeddingElement.contentDocument. From there, the SVG element can be accessed and click event handlers can be installed.

Implementation note: in the demo, I add event handlers to all path elements. For performance reasons, you would probably want to add a single event handler to the SVG and then use the event target in the handler. Edit: like in this updated Fiddle.

Old answer

A quick Google search brought me here. I think that's the answer to your problem, right?

To summarize here: it is not possible to capture events on an embed element, unfortunately the only solution is modifying the SVG file.

Here is a small example of how to embed JavaScript into an SVG file (JSFiddle). It is based on an example from IBM developerWorks.

<svg>
  <script type="text/javascript">
    <![CDATA[
    var redVal = 0;
    var greenVal = 0;
    var blueVal = 0;

    function changeCol(evt) {
       redVal = Math.round(Math.r
answered 2012-03-30T14:52:04.000

Your Answer