views:

51

answers:

2

(using http://code.google.com/p/svgweb/)

window.onsvgload = function() {
  function onEnter(e) {          
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
      targ = targ.parentNode;

    alert(targ.hasAttributeNS(null, 'id')); //displays false
    alert(targ.getAttributeNS(null, 'id')); //displays a blank dialog
    alert(targ.id); //displays a blank dialog
  }

  /* Seldom_Seen is a group element in the SVG - <g id="Seldom_Seen">... */
  document.getElementById('Seldom_Seen').addEventListener("mouseover", onEnter, false); //alert is blank
  document.getElementById('normal_dom_element').addEventListener("mouseover", onEnter, false); //alert displays id as expected
}

The event listening works for SVG elements. I just can't seem to get the id. I can get other object properties like the x,y values. Anyway to get the ID of the targeted element?

+1  A: 

maybe

e.currentTarget

but with jQuery, it is simply

window.onsvgload = function() {
  $('#Seldom_Seen').mouseover(function(){ onEnter(this); });
  $('#normal_dom_element').mouseover(function(){ onEnter(this); });
}

function onEnter(obj) {
  alert($(obj).attr("id"));
}
yomash
This worked: e.currentTarget.idThanks!
Chris
+1  A: 

It's quite possible that you get another target than you expect. Do all your elements inside the 'Seldom_Seen' element have id's? You can always alert the target to see what type of element it is.

There are some gotchas with mouseover/mouseout on <g> elements too, the events bubble and you may get them twice unless you do some filtering. See slides 17 and 18 here for a possible workaround.

Erik Dahlström
Interesting. I'm not exactly sure how to do the 'filtering.' Calling e.currentTarget.id worked for me. But I wonder if event bubbling will still cause some issues.
Chris
If you have multiple elements inside the 'g' that you want to capture events on, but also capture events on the 'g' then you'll probably need to worry about this. Otherwise you should be all set.
Erik Dahlström