Reputation: 759
I have an svg on my site for selecting states in the US. The format is:
<svg...>
<a xlink:href="...">
<polygon ...><title>{stateName}</title></polygon>
</a>
</svg>
After several hours of headaches trying to figure out why clicking the links caused issues with other scripts on the same site, I narrowed down the issue to the event not being passed to those functions when the target was the anchor in the svg.
So I created a separate page without those other scripts and experimented by creating the following function:
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('svg a').click(function(event){
if(event.target.tagName == 'polygon'){
var target = $(this).parent();
alert('target: ' + dump(target));
}else{
alert('event: ' + dump(event.target));
}
});
});
})(jQuery);
</script>
Note: The dump() function is a custom function that outputs the contents of objects and arrays.
My first version of this code just output the event.target.tagName which was always "polygon" even though the object I'm binding the click to is the anchor. So I modified it to get the polygon's parent but that returns the svg. It's like the anchor doesn't exist.
Why is it that I cannot seem that the event for that function doesn't contain any reference to the anchor? How can I get this to behave like it would if the anchor was inside a div instead?
I tried a jQuery SVG plugin but that did nothing.
TL;DR / Clarification The issue isn't that the anchor isn't working, clicking it will take you to the page defined in xlink:href. But any jQuery code bound to click events that are triggered when clicking these anchors within the svg either come through with the event as undefined or not containing the expected anchor object data.
How can I get the appropriate event object for these anchors?
Edit: Finally got jsfiddle to load: http://jsfiddle.net/fja4Lt0L/
Explanation of current behavior in different browsers:
None of those are behaviors expected of the script or intended by the coder.
Upvotes: 0
Views: 1715
Reputation: 124016
In SVG only graphics elements (lines, rectangles etc and text) can be the target of events. If you specify it on a container e.g. a <g>
or <a>
element then all their children become targets.
Just call .parentElement
(if you're using raw DOM) or .parent()
(if you're using jQuery) repeatedly on whatever the target is till you get an anchor element.
Here's an example or with jquery and .parent
Upvotes: 2