Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why getBoundingClientRect gives different values in IE and Firefox

I have an Image control and I need to place some elements on top of the image control. when I used getBoundingClientRect() it is working in IE(7,8 and 9) but It is giving different values in Firefox and Chrome. Is there any other function available for getting the Bounding rectangle of an element ?

like image 794
Senan Avatar asked Apr 19 '12 14:04

Senan


People also ask

What does getBoundingClientRect return?

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.

Does getBoundingClientRect include padding?

Border, padding and margin are not included. This means when you set a width, That width is set to the content only then you add the padding and border.


2 Answers

Citation from old IE documentation for getBoundingClientRect: "In Microsoft® Internet Explorer 5, the window's upper-left is at 2,2 (pixels) with respect to the true client." This still seems to be valid.

In IE9 usage of <meta http-equiv="x-ua-compatible" content="ie=edge"/> "sets" the upper-left corner to it's right position (0,0).

As d4rkpr1nc3 answered, you can get those values by other methods, but the results depend on the used browser too. I think you'll need a slightly different approach to this problem. Check the code below, it might give you some ideas.

<DIV id="imagecontrol" style="position:absolute;width:200px;height:200px;">
  <DIV id="topleft" style="position:absolute;width:100px;height:100px;left:0px;top:0px;"></DIV>
  <DIV id="topright" style="position:absolute;width:100px;height:100px;right:0px;top:0px;"></DIV>
  <DIV id="bottomleft" style="position:absolute;width:100px;height:100px;left:0px;bottom:0px;"></DIV>
  <DIV id="bottomright" style="position:absolute;width:100px;height:100px;right:0px;bottom:0px;"></DIV>
</DIV>
like image 93
Teemu Avatar answered Sep 18 '22 19:09

Teemu


The values maybe slightly different in different browsers but getBoundingClientRect() is still your best bet for performance and accuracy. The coordinates it returns are relative to the viewport rather than the document, however, so you'll need to account for that using scroll values on the window / document.

Here's a good blog post about this:

http://weblogs.asp.net/bleroy/archive/2008/01/29/getting-absolute-coordinates-from-a-dom-element.aspx

David Mark is good on this stuff. Here's a tip of his from comp.lang.javascript:

https://groups.google.com/forum/?fromgroups#!topic/comp.lang.javascript/zWJaFM5gMIQ

like image 31
Tim Down Avatar answered Sep 21 '22 19:09

Tim Down