mgalardini
mgalardini

Reputation: 1467

How to add event listeners to objects in a svg?

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?)

Upvotes: 27

Views: 47080

Answers (1)

methodofaction
methodofaction

Reputation: 72465

This 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);

Upvotes: 24

Related Questions