Skip to content
Advertisement

getBoundingClientRect returning wrong results

I’m struggling a little trying to determine the current location and size of an element within the DOM. I’ve put together a fragment to illustrate a card based system down the right hand side of the screen.

The behavior that I’m trying to build is that when you click on one of those cards, another card will be added (ultimately underneath, but on top for now) which will fly out to the top left corner of the screen before filling the available space.

JavaScript
JavaScript
JavaScript

What I am doing is fairly basic, grab the clicked element, measure it’s bounding rectangle and adding a new element to the body with the same size and position:

JavaScript

I’ve been reading about getBoundingClientRect() and it seems to do what I want according to the spec, it’s just not doing what I expect it to here as the width/height are all off, and Firefox can’t even get the left correct. Is this function simply broken (which would surprise me) or is some of my CSS somehow breaking this native function?

I should add here is a screenshot of the results being off in different browsers. IE is by far the nearest but still seems to struggle with the bottom/right values.

enter image description here

Advertisement

Answer

Well I’m mightily confused but managed to get the thing working as I wanted. I changed the calculation to take into account padding, margin and borders based on a little guess work, and modifying some styles to verify it all still worked. This gave me the following calculation:

JavaScript

Oddly though when I tried plugging this into my application it didn’t work at all. Taking out some of the padding and ended up with:

JavaScript

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement