user18015
user18015

Reputation:

Is there a way to get the bounding box (in pixels) of a DOM element?

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.)

Upvotes: 8

Views: 14912

Answers (2)

Aletheios
Aletheios

Reputation: 4020

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:

Upvotes: 12

wecsam
wecsam

Reputation: 2751

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 

Upvotes: 1

Related Questions