Reputation: 242
I want to know how I can extract the information if one element in the SVG DOM tree contained in a different element of the same tree.
In my case I want to execute onClick events on the different elements of the SVG tree. Since the SVG graph is issued by a server and contains several thousand elements I thought it is not feasible to register a distinct event with each node. So my idea was to register the event with the root node of the SVG and then determine from the target of the event which element was clicked on. This works fine so far.
In the next step I want to open a pop-up frame to display information about the SVG element I clicked on. The frame shouldn't open when the event came from an area of the SVG image where no element is placed.
After reading the documentation I thought it would be a good idea to use the jQuery method contains (http://api.jquery.com/contains-selector/) however it yields false as a result all the time and I don't know what is wrong. The ($(svgRoot).find(svgElement).length
method also does not work. Does someone has an idea what is wrong?
Here is an example of the problem in jsfiddle: https://jsfiddle.net/gjvaz346/1/
Here is the SVG graph:
<svg id="svg-element" currentScale="1" viewBox="0 0 100 100">
<g id="svg-root" transform="scale(0.5)">
<rect id="blue-rectangle" style='fill:blue;opacity:1' x='10' y='10' width='70' height='40' />
<rect id="green-rectangle" style='fill:green;opacity:1' x='60' y='30' width='40' height='40' />
</g>
</svg>
Here is the event handler method:
function svgCanvasClicked(evt) {
var target = evt.target;
var svgElement = $(target.id);
var svgRoot = $('#svg-root');
console.log(target.id);
console.log(svgRoot.id);
console.log($(svgRoot).find(svgElement).length);
console.log($.contains(svgRoot, svgElement));
}
Greetings
Upvotes: 0
Views: 2169
Reputation: 74420
Easiest way is to bind click
event on rect
element but delegating it to svg
element, so only one event would be bound:
$('#svg-element').on('click', 'rect', handler);
Then inside handler
method, this
will refer to the clicked rect
;
Upvotes: 1