Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
<g id="polygonGroup" transform="translate(80, 50)">
<polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"></polygon>
<polygon points="10,-10 35,-30 60,-10 60,30 10,30"></polygon>
<polygon class="origin" points="-4,0 0,4 4,0 0,-4"></polygon>
<g id="textGroup" transform="translate(80, 50)">
<text x="-35" y="10">Text</text>
<text x="35" y="10">Text</text>
and this simple jQuery click event handler:
function clicked(event) {
console.log(event.offsetX, event.offsetY);
$('svg').click(clicked);
as seen here: https://jsfiddle.net/1ht0L8y6/6/ have different behaviors in different browsers:
Chrome: The coordinates are based on the top left of the SVG element, no matter where I click inside the SVG. This is the behavior I want.
Firefox: The coordinates are based on the top left of whatever element I'm in, which may be SVG, polygon, or text.
IE and Edge:
When in the SVG but not in any of its sub-elements, the coordinates
are based on the SVG element.
When in a polygon, the coordinates are
based on the origin of the <g>
group, with its translate
offset
(i.e., the black diamond). Negative coordinates are possible this way,
unlike in Chrome or Firefox.
I have observed a different behavior for
text elements in these browsers: They would give coordinates based on
the bottom middle of the text element. But I couldn't manage to
reproduce this in the fiddle; in the fiddle text elements behave
the same as polygons in these browsers.
What is a reliable cross-browser way to get the coordinates of the click?
–
<g id="polygonGroup" transform="translate(80, 50)">
<polygon points="-60,-10 -35,-30 -10,-10 -10,30 -60,30"></polygon>
<polygon points="10,-10 35,-30 60,-10 60,30 10,30"></polygon>
<polygon class="origin" points="-4,0 0,4 4,0 0,-4"></polygon>
<g id="textGroup" transform="translate(80, 50)" fill="red">
<text x="-35" y="10">Text</text>
<text x="35" y="10">Text</text>
To read more about mouse detection in SVG I recommend this book: Using SVG with CSS3 and HTML5: Vector Graphics for Web Design
I hope it helps.
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.