SivaRajini SivaRajini - 6 months ago 180
CSS Question

how to get bounding box for div element in jquery

i want to calculate bounding box for div element via jquery/javascript.

i tried like this .

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


it returns some values. whether it is correct way to get bounding box for div element via
jquery / javascript
.

i need something like
getBBox()
method in
SVG
element. it will return x,y ,width and height of an element. sameway how can i get bounding box for div element.

Thanks,

Siva

Answer

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

Comments