Reputation: 15
I have some SVG images on my html page. I want get id of each image by click on it. HTML:
<div class = "svgLoading"><object data="images/91.svg" type="image/svg+xml" id = "47"></object></div>
<div class = "svgPoints"><object data="images/30.svg" type="image/svg+xml" id = "48"></object></div>
I'm trying to get them like this:
document.body.onclick = function(event) {
var target = event.target || event.srcElement;
alert(target.tagName); }
Its working fine for other elements, for example: img, div without object. But clicking on the svg is ignored. Why is this happening and how to properly handle clicks on svg?
Upvotes: 0
Views: 553
Reputation: 1751
The tag can not be clicked but you can make a workaround and set the click action to parent. ( Take a look at this SO question )
Set the object pointer-events to none, in order to make the element to be never the target of pointer events:
The element is never the target of pointer events; however, pointer events may target its descendant elements if those descendants have pointer-events set to some other value. In these circumstances, pointer events will trigger event listeners on this parent element
$("#svg_47").click(function(target) {
var target = event.target || event.srcElement;
console.log("object id: " + target.firstElementChild.id)
alert(target.tagName);
});
object {
width: 100%;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="svgLoading" id="svg_47">
<object data="https://css-tricks.com/wp-content/uploads/2015/05/kiwi.svg" type="image/svg+xml" id="47"></object>
</div>
<div class="svgPoints" id="svg_87">
<object data="https://svgsilh.com/svg/1801287.svg" type="image/svg+xml" id="48"></object>
</div>
Upvotes: 4