3

I have a grid of floated, fixed-sized boxes in a container. I need to get the position of each box relative to the container using JS/jQuery. I know I can set position: relative on the container and use jQuery $box.position(), but it doesn't work because my <body> is scaled using transform: scale(). (I have another script that scales the <body> to match the viewport width, similar to this, but for this question, just know that the <body> will have transform: scale() with some arbitrary scaling factor.)

jQuery's $box.position() seems to return the position after scaling, but I want the original position before scaling. For example, if each box has width: 300px; margin-right: 10px, then a box in the third column should have left offset 620px (before scaling). However, $box.position().left gives 310px (after scaling) if the <body> has transform: scale(0.5).

Is there a way to get the position before scaling, without knowing the scaling factor? I found the native DOM method getBoundingClientRect(), but (1) it still gives the position after scaling and (2) it's relative to the viewport rather than the container.

Thanks.

DynamicDispatch
  • 421
  • 4
  • 12
  • i'm confused. You asked a question and answered it at the same time? Are you essentially posting it out here so that it may help others in the future? – Observer Jun 17 '16 at 21:58
  • 1
    @Observer, yes actually, that's the idea. StackOverflow encourages users to answer their own questions: https://stackoverflow.com/help/self-answer . When you ask a question, there's an "Answer your own question" checkbox at the bottom, which allows you to submit a question and answer at the same time. This is actually my first time doing so. Just wanted to contribute back to StackOverflow after learning so much from this website. =) – DynamicDispatch Jun 17 '16 at 22:36
  • Cool, Thanks for answering my comment-question! – Observer Jun 20 '16 at 17:10

1 Answers1

2

Try to use the native DOM properties offsetLeft and offsetTop instead. Browser support looks good: basically all browsers and IE8+. I tried these properties and they seem to give the correct position before scaling in Chrome, Firefox, and IE11 at least.

Because they're native DOM properties, you need $element[0] to get the underlying DOM element first: $box[0].offsetLeft and $box[0].offsetTop. Also, note that they give the position of the top-left corner of the element's border box, not margin box.

DynamicDispatch
  • 421
  • 4
  • 12
  • This was exactly what I was looking for! Seemed simple enough, just give me the position before the `transform: scale` happens, but all the answers I was finding were pages of JS code!! Luckily I found yours. Thanks man! – Fuad Zeyad Tareq Jan 24 '23 at 17:48