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 ?
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.
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.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With