Skip to content Skip to sidebar Skip to footer

Add Click Event On Elements Of An Embedded Svg In Javascript

I got this SVG image from Wikipedia and embedded it into a website using this code: If you run this, you can inspect the ele

Solution 1:

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.

Solution 2:

If your SVG is contained in the DOM, you can attach event listeners to separate elements in the same manner as basic HTML. Using jQuery one example would be: http://jsfiddle.net/EzfwV/

Update: Most modern browsers support inline svg, so to load your source into the DOM, all you have to do is load it in from a resource, (using something like jQuery's load()).

Edit: more specific example http://jsfiddle.net/EzfwV/3/

Solution 3:

Okay using your comments I found an answer to my problem. I added this code in the svg itself.

<scripttype="text/javascript"> <![CDATA[
    functionaddClickEvents() {
        var countries = document.getElementById('svg1926').childNodes;
        var i;
        for (i=0;i<countries.length;i++){
            countries[i].addEventListener('click', showCountry);
        }
    }

    functionshowCountry(e) {
        var node = e.target;
        if (node.id != 'ocean') {
            node = getCorrectNode(node);
        }
        alert(node.id);
    }

    functiongetCorrectNode(node) {
        if (node.id.length == 2 || node.id == 'lakes') {
            return node;
        }
        returngetCorrectNode(node.parentNode);
    }
]]> </script>

The function addClickEvents is triggered when the svg loads. But I still have another problem with this. I have to embed this svg (with the code) into a HTML document using

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

Instead of alerting the id, I have to place it into a div in the HTML document. How do I get this id from the svg?

Solution 4:

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><scripttype="text/javascript">
    <![CDATA[
    var redVal = 0;
    var greenVal = 0;
    var blueVal = 0;

    functionchangeCol(evt) {
       redVal = Math.round(Math.random() * 255);
       greenVal = Math.round(Math.random() * 255);
       blueVal = Math.round(Math.random() * 255);
       evt.target.setAttribute("fill",
             "rgb(" + redVal + "," + greenVal + "," + blueVal + ")");

    }
    // ]]></script><circlecx="200"cy="200"r="100"fill="blue"onclick="changeCol(evt)" /></svg>

Solution 5:

A simple method is

  • Creating Path dynamically in SVG with javascript
  • Adding Styles Dynamically
  • Adding Events to Path
  • Appending to existing SVG.

Script

 <svg id="mySvg"></svg>

varXMAX = 500;
varYMAX = 500;
var _xx=10;
var _reg=100;
var _l=10;
// Create PATH elementfor(var x=1;x<20;x++)
{
var pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
pathEl.setAttribute('d','M'+_l+' 100 Q 100  300 '+_l+' 500' );
pathEl.style.stroke = 'rgb('+(_reg)+',0,0)';
pathEl.style.strokeWidth = '5';
pathEl.style.fill = 'none';
    $(pathEl).mousemove(function(evt){$(this).css({"strokeWidth":"3","stroke":"#ff7200"}).hide(100).show(500).css({"stroke":"#51c000"})});

$('#mySvg').append(pathEl);
_l+=50;
}

Live Demo in JSFiddle

Post a Comment for "Add Click Event On Elements Of An Embedded Svg In Javascript"