Getting on click position of SVG elements loaded from svg file

1,008 views
Skip to first unread message

Jordi Tost

unread,
Sep 3, 2015, 11:24:48 AM9/3/15
to Snapsvg
Hi everybody,

In my code I load an SVG file with many elements inside. To some of the elements I have added a click event handler.

After clicking one of these elements, I need to display a popup relative to the element, but I haven't found a way to do this. The ideal would be to get the X and Y position of the element, relative to the main SVG element.

To get this, I use the getBBox() function, but it seems to return erroneous values, since some elements return the [0, 0] coordinates, although they are not in this position.

Here is my code:

var svg = Snap("#house");

Snap.load("images/house/optimised.svg", function (f) {

var g = f.select("g"),
    lamp = f.select("#Lamp"),
    laptop = f.select("#Laptop"),
    wc = f.select("#WC"),
    sink = f.select("#Sink");

/////////////////
// Interaction
/////////////////

lamp.click(onElementClicked);
laptop.click(onElementClicked);
wc.click(onElementClicked);
sink.click(onElementClicked);

// Click on the whole graphic
$(document).click(function(e) {
     $('.active-graphic').removeAttr("class");
});

// Add loaded graphic (g) to svg element (svg)
svg.append(g);
});

var onElementClicked = function(evt) {

        var x = this.getBBox().x,
            y = this.getBBox().y;

        console.log("x: " + this.getBBox().x + ", y: " + this.getBBox().y);

activateGraphic(this);
evt.stopPropagation();
}

Thanks in advance for your support!

Ian

unread,
Sep 3, 2015, 11:57:23 AM9/3/15
to Snapsvg
You probably will need to get slightly dirty with matrices, or at least Snap ones. Here's a question on SO I answered the other day which had something similar, although the question already sort of has the answer there.


You will probably need to take into account existing transforms.

If you can get an example on a jsfiddle it should be possible to sort it.

Ian

Jordi Tost

unread,
Sep 3, 2015, 12:54:41 PM9/3/15
to Snapsvg
Hi Ian,

Thanks for your fast response :)

From one hand, this solves one of my problems. But in the other hand, when getting the x and y positions from the clicked elements with getBBox(), some elements have x=0 and y=0, although they are not positioned in this positon.  (not the on mouse click position but the position of a given graphic element inside the SVG). This is what I do inside the onElementClicked function in the code I pasted in the question.

I will prepare a jsfiddle for you.

Thanks again!
Reply all
Reply to author
Forward
0 new messages