0

I am trying to get the coordinates of the box on the image. The coordinates should be based on the image itself and not on the screen size. I am currently using getBoundingClientRect(). How do I retrieve the coordinates based on the image, the box is on, rather than the window size?

CODE that I've tried:

var rect = div[index].getBoundingClientRect();

I found this post on SO : How to get xy coordinates of child element from parent element in jquery? but it was 7 years ago...

user2226755
  • 12,494
  • 5
  • 50
  • 73
PandaB3ar
  • 45
  • 10

1 Answers1

-1

You would use the difference between the elements position and its containers position. I've used getBoundingClientRect and returned a new DomRect like you were trying but be cautions as there is no support for Internet Expolorer, Edge or Safari at the moment.

const getBoundingClientRect_RelativeToParent = element => {
  const domRect = element.getBoundingClientRect(),
    parentDomRect = element.parentElement.getBoundingClientRect()

  return new DOMRect(domRect.left - parentDomRect.left, domRect.top - parentDomRect.top, domRect.width, domRect.height)
}

console.log(getBoundingClientRect_RelativeToParent(document.querySelector(".child")))
.parent {
  width: 500px;
  height: 300px;
  margin-left: 200px;
  margin-top: 200px;
  padding-left: 30px;
  padding-top: 30px;
  background: green;
}

.child {
  width: 100px;
  height: 50px;
  background: red
}

body {
  background: blue
}
<div class="parent">
  <div class="child">
  </div>
</div>
BlueWater86
  • 1,773
  • 12
  • 22