Javascript – Add click event on elements of an embedded SVG in javascript

canvashtmljavascriptsvg

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?

Best Solution

Here's an example that should be very similar to what you're trying to do. It uses <object> instead of <embed>, but that's only a minor detail. See this other example for how to get to the DOM of the embedded document from the parent document, it differs just a bit between the two.

Also note that the svg maps that wikipedia have are quite large, so you will want to optimize the svgs before actual usage on a live website, try e.g SVG Cleaner or SVG Scour.