views:

142

answers:

2

Hi,

How do I locate an element within SVG in Opera, given coordinates?

elementFromPoint(x,y) works fine with Firefox, but seems to fail with Opera, returning always the whole SVG and not the particular element.

One might wonder why do I need it at all. Well, simply because I'd like to highlight the SVG element under the cursor, and because Opera doesn't fire any event when an element under the cursor is added/deleted, before you make a move with a mouse. That is, when I add a new element, it is not highlighted before I move the mouse slightly, which doesn't look nice.

Cheers, Mikhail.

+1  A: 

In Opera there is SVG1.1's SVGSVGElement.getIntersectionList.

var element= document.elementFromPoint(pageX, pageY);
if (element.localName.toLowerCase()=='svg' && 'getIntersectionList' in element) {
    var svgxy= Element_getPageXY(svg); // by the usual offsetLeft/offsetParent etc. method
    var rect= svg.createSVGRect();
    rect.x= pageX-svgxy[0];
    rect.y= pageY-svgxy[1];
    rect.width=rect.height= 1;
    var hits= svg.getIntersectionList(rect, null);
    if (hits.length>0)
        element= hits[hits.length-1];
}

[Untested code, might even work.]

bobince
Works fine, thanks a lot!The 'svg' variable is actually the 'element' one. For getPageXY I used the script from http://www.quirksmode.org/js/findpos.html, is anybody's interested.
Qnan
A: 

A way to do what you want without needing to look for the element under the cursor yourself is demonstrated in this example. Basically, you bind an event handler for the mouseover event to the root document element, then inspect the event's target to find out which element actually received the event.

For production code, you should add logic to take care of situations where the element is a <use> reference (by using target.correspondingUseElement to find out the id).

dep