I would like to create a web page displaying an interactive svg: since several svg may be used, the various objects displayed will have different IDs, so the event listeners (to catch a mouse click, for example) have to be dynamic.
Starting from this snippet
var a = document.getElementById("alphasvg");
a.addEventListener("load",function(){
var svgDoc = a.contentDocument;
var delta = svgDoc.getElementById("delta");
delta.addEventListener("click",function(){alert('hello world!')},false);
},false);
I would like to find a way to cycle through all the objects of the svg (maybe having a particular class) and attach an even listener to them.
update
So JQuery 'each' function may be a suitable option, but it seems that JQuery doesn't handle the svg DOM so well. Is there any other available option? (like a JQuery plugin?)
I would like to create a web page displaying an interactive svg: since several svg may be used, the various objects displayed will have different IDs, so the event listeners (to catch a mouse click, for example) have to be dynamic.
Starting from this snippet
var a = document.getElementById("alphasvg");
a.addEventListener("load",function(){
var svgDoc = a.contentDocument;
var delta = svgDoc.getElementById("delta");
delta.addEventListener("click",function(){alert('hello world!')},false);
},false);
I would like to find a way to cycle through all the objects of the svg (maybe having a particular class) and attach an even listener to them.
update
So JQuery 'each' function may be a suitable option, but it seems that JQuery doesn't handle the svg DOM so well. Is there any other available option? (like a JQuery plugin?)
Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Sep 17, 2012 at 0:26 mgalardinimgalardini 1,4672 gold badges18 silver badges31 bronze badges1 Answer
Reset to default 24This is my preferred structure for adding event listeners to SVG elements with vanilla js...
// select elements
var elements = Array.from(document.querySelectorAll('svg .selector'));
// add event listeners
elements.forEach(function(el) {
el.addEventListener("touchstart", start);
el.addEventListener("mousedown", start);
el.addEventListener("touchmove", move);
el.addEventListener("mousemove", move);
})
// event listener functions
function start(e){
console.log(e);
// just an example
}
function move(e){
console.log(e);
// just an example
}
The sample code you present is somewhat contrived, but here's a rewrite that makes it work...
var a = document.getElementById("alphasvg");
a.addEventListener("load",function(){
var svgDoc = a.contentDocument;
var els = svgDoc.querySelectorAll(".myclass");
for (var i = 0, length = els.length; i < length; i++) {
els[i].addEventListener("click",
function(){ console.log("clicked");
}, false);
}
},false);