john k
john k

Reputation: 6615

How do I dynamically attach event handlers to SVG groups?

Adding event handlers to SVG groups (<g> tags) is resulting in strange behaviors. It appears to be broken. Here's the relevant code:

var newelement = document.createElementNS("http://www.w3.org/2000/svg", 'use');
newelement.setAttributeNS('http://www.w3.org/1999/xlink', 'href', "#Xprototype");
var newgroup = document.createElementNS("http://www.w3.org/2000/svg", 'g');
newgroup.appendChild(newelement);
newgroup.setAttribute("transform", "translate(100, 100)");
var svg = document.getElementById("thesvg");
newgroup.addEventListener("click", elementClick, false); //Click handler is set to the GROUP, not the element
svg.appendChild(newgroup);

Here's the fiddle:

http://jsfiddle.net/3bey8heu/2/

I have no problem adding event handlers to other objects - it seems to be unique to dynamically created groups. And yes, groups can handle mouse events, as seen in this fiddle.

Upvotes: 2

Views: 814

Answers (1)

Robert Longson
Robert Longson

Reputation: 123996

Only graphics elements can be the target of pointer-events such as click. If you set it on a parent such as a <g> element then all its graphical children become possible targets but not the <g> itself.

Upvotes: 3

Related Questions