8

Is there a way to get the bounding box coordinates of a DOM element with Javascript?

Obviously I can calculate it from various CSS properties: width, height, and so on.

I’m asking because there are many other graphical platforms that provide this as a method. For instance apparently it can be done in XUL as per this post, which describes a method getBoundingClientRect().

(My goal is to check whether two elements overlap.)

Community
  • 1
  • 1
  • Is this a duplicate post or are these posts not solutions to your question? - http://stackoverflow.com/questions/4230029/jquery-javascript-collision-detection - http://stackoverflow.com/questions/2440377/javascript-collision-detection When I read this, they did sound similar. Hope those help. – shanabus Feb 15 '12 at 03:49

2 Answers2

12

Actually, there is a built-in method to get the bounding rectangle: Element.getBoundingClientRect

The method returns an object containing the (visual) top, right, bottom, and left coordinates of the element as well as its width and height.

Example (JSFiddle)

More info:

Aletheios
  • 3,960
  • 2
  • 33
  • 46
1

Let's say that your DOM element had the ID myElement.

document.getElementById("myElement").offsetLeft; //Left side of box 
document.getElementById("myElement").offsetTop;  //Top side of box 
document.getElementById("myElement").offsetLeft 
    + document.getElementById("myElement").offsetWidth; //Right side of box
document.getElementById("myElement").offsetTop
    + document.getElementById("myElement").offsetHeight; //Bottom side of box 

For the bottom and right sides, the code basically adds the width or height of the bounding box to the left or top side.

If you wanted to, you could define document.getElementById("myElement") once and use the reference, as follows:

var myElement = document.getElementById("myElement");
myElement.offsetLeft; //Left side of box 
myElement.offsetTop;  //Top side of box 
myElement.offsetLeft + myElement.offsetWidth; //Right side of box
myElement.offsetTop + myElement.offsetHeight; //Bottom side of box 
wecsam
  • 2,651
  • 4
  • 25
  • 46