How to get bounding box for div element in jQuery

120,301

Solution 1

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.

Solution 2

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Solution 3

using jQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]
Share:
120,301
SivaRajini
Author by

SivaRajini

Passionate to write code in jquery and MVC/C#.having curiosity to learn advanced concepts in jquery as well MVC

Updated on April 03, 2021

Comments

  • SivaRajini
    SivaRajini about 3 years

    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?

  • SivaRajini
    SivaRajini almost 11 years
    yes thanks i knew this concept. am asking about whether it is correct way to get bounding box of an element ?
  • Mr_Green
    Mr_Green almost 11 years
    I suggest using outerWidth() instead of just width(). So that, it will consider the padding value if any.
  • Vladimir Panteleev
    Vladimir Panteleev over 9 years
    Be aware that getBoundingClientRect will return coordinates relative to the viewport, and not the document or parent.
  • Rycochet
    Rycochet almost 9 years
    This doesn't take into account css transform - so doesn't give the correct answers if that's used. It could also be optmised by caching the offset() result.
  • Dariel Pratama
    Dariel Pratama over 7 years
    what if the element has absolute position?