upog
upog

Reputation: 5526

Get X,Y position of element in Javascript

I want to find X,Y position of mouse click relative to SVG element. The SVG element will be embedded in HTML.

var svg = document.getElementById("svg1");
svg.addEventListener('click', event => {
  let x = event.clientX;
  let y = event.clientY;
  console.log(x, y);
});
html {
  height: 100%
}

body {
  height: 100%;
  display: flex;
  justify-content: center;
  background-color: #fff;
}

svg {
  height: 100%;
  background: grey;
}
<svg id="svg1" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="#52c927" />
    <circle cx="50" cy="50" r="25"   fill="white" />
    <circle cx="50" cy="50" r="15"  fill="red" />
</svg>

Want to subract offsetLeft and offsetTop of SVG before printing X and Y in console. But not able to get those value

Upvotes: 2

Views: 3873

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

To get an element coordinates or size use Element.getBoundingClientRect

event.target.getBoundingClientRect() or event.currentTarget.getBoundingClientRect() (for the element bound to the listener, rather than the one who propagated the event). Or directly with your cached Element reference constant svg.getBoundingClientRect()

const bcr = event.target.getBoundingClientRect();
console.log(bcr.left, bcr.top)

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

In your specific case, to get the relative mouse coordinates:

var svg = document.getElementById("svg1");
svg.addEventListener('click', event => {
  const bcr = event.target.getBoundingClientRect();
  const relative_x = event.clientX - bcr.left;
  const relative_y = event.clientY - bcr.top;
  console.log(relative_x, relative_y);
});

Upvotes: 3

17axaH
17axaH

Reputation: 484

You can get the coordinates relative to the element like this:

var svg = document.getElementById("svg1");

svg.addEventListener('click', event => {
  const rect = svg.getBoundingClientRect();

  let x = event.clientX - rect.left;
  let y = event.clientY - rect.top;

  console.log(x, y);
});
html {
  height: 100%
}

body {
  height: 100%;
  display: flex;
  justify-content: center;
  background-color: #fff;
}

svg {
  height: 100%;
  background: grey;
}
<svg id="svg1" viewBox="0 0 100 100">
    <circle cx="50" cy="50" r="40" fill="#52c927" />
    <circle cx="50" cy="50" r="25"   fill="white" />
    <circle cx="50" cy="50" r="15"  fill="red" />
</svg>

Upvotes: 0

Related Questions