Reputation: 1631
I have this SVG file. which display different svg elements (Circle, Eclipse, Polygon,polyline etc)
and each element has its own ID.
I can add the function (onClick or MouseClicK) when that specific ID is clicked.
Is there any way to add a common function (in JavaScript or Jquery) which respond to click event and tells us from which object (ID) click originates?
So I need:
HTML code to add/reference SVG file. Not sure if I use SVG or Object tag? Which one works in all browsers?
And then JQuery of JavaScript which respond to mouse click on the elements and tell which ID has been clicked?
If you see following SVG it has different circles which has ID e.g. 01, 02, 03 etc.
http://imgh.us/ClockControl.svg
Upvotes: 4
Views: 5335
Reputation: 16505
The simplest way is to print the svg directly into the html. This way each SVG Element is a »real member« of the DOM.
<html>
<head>
…
</head>
<body>
…
<!--
this stands for the content of »ClockControl.svg«
open it in a text editor, copy all the content, beginning at
<svg and paste it into the html
-->
<svg id="your-svg">
…
<path id="e1" d="…" />
…
</svg>
</body>
</html>
Next thing is event handling, what could be done something like that (on load):
var svg = document.querySelector('svg#your-svg'),
handlers = {
'e1' : function(e){ … }
};
svg.addEventListener('click', function(e) {
var c = e.target;
while (c !== svg) {
if (c.hasAttribute('id') {
var id = c.getAttribute('id');
if (handlers.hasOwnProperty(id)) {
handlers[id](c);
break;
}
}
c = c.parentNode;
}
});
If you are not familiar with all the ways an SVG can inserted into the HTML have a look here. The method used in this answer in called »inline SVG«.
Upvotes: 4
Reputation: 8597
You can use the following code (just vanilla JavaScript with no use of jQuery), which adds an event listener click
on every SVG element in your page.
document.querySelectorAll('svg').forEach(function(item){
item.addEventListener('click', function(event){alert('svg clicked was: ' + event.target.id)});
})
#circle{
position:absolute;
}
#rect{
position:absolute;
left: 0;
top: 100px;
transform: translate(80px, 80px)
}
Click on one of the following SVG shapes.
<svg height="500" width="500">
<circle id="circle" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
<rect id="rect" width="100" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)">
Sorry, your browser does not support inline SVG.
</svg>
Upvotes: 1
Reputation: 2571
You can use jQuery to get the id
$('svg').click(function(){
alert('element ID is: '+this.id);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<svg id="1" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<svg id="2" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="blue" />
</svg>
Upvotes: 0