Sharovatov’s Weblog

Useful JS tips – getBoundingClientRect()

Posted in javascript by sharovatov on 12 June 2009

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!


Share :

About these ads
Tagged with: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: