Useful JS tips - getBoundingClientRect()

What do you use to get element’s offset? Looping through its parents and summing offsetLeft/offsetTop numbers? I bet you had problems with it. Well, I did, especially when additional positioning context was generated by an element with position!=static.

10 years ago in IE5.0 Microsoft invented a better way - getBoundingClientRect() method.

It’s been popularised by PPK, specified in cssom-view spec, copied by Firefox 3, Opera 9, Chrome 2, Safari; used in jQuery.

element.getBoundingClientRect() basically returns the object containing this element’s coordinates according to the window element. So you don’t have to do a loop, just call this method once and get the results. The only thing it doesn’t count for is scrolling offset, which can be calculated easily.

Extremely useful, thanks Microsoft IETeam!

comments powered by Disqus