Spot the bug: JavaScript positioning

by timvasil 11/17/2007 6:20:00 PM

Can you spot the bug in the following function--designed to get the absolute position of an element on a webpage?

function getLocation(obj)
{
 var curleft = curtop = 0;
 for (; obj; obj = obj.offsetParent)
 {
  curleft += obj.offsetLeft;
  curtop += obj.offsetTop;
 }
 return [curleft, curtop];
}

Here's a hint:  under normal operation it works fine. 

Here's another hint:  it involves IE "expressions."

So, what's the problem?  It comes down to this line of code:

 var curleft = curtop = 0;

Here curleft is defined as a local variable, but curtop is not!  curtop is actually synonymous with this.curtop, so it's a property of this, not a local variable.  Imagine what would happen if getLocation() were called recursively; the nested call would essentially change the value of curtop before returning, the outer function would return a bogus "top" value.  But there's no recursive call so there's no problem, right?  In my case, wrong!  Apparently as you access offsetLeft and offsetTop properties, IE may decide to evaluate expressions.  And if you've so happened to define an expression that calls getLocation(), you're suddenly making a non-obvious recursive call.  For example:  <div style='top:expression:getLocation(document.all.element)'></div> will trigger the bug.

The fix is to declare the variables this way instead:

 var curleft = 0; 
 var curtop = 0;

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

JavaScript

Related posts

Comments are closed

 

About the author

Tim Vasil Tim Vasil
I'm a software engineer living in Cambridge, MA.

E-mail me Send mail

Search

Calendar

<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910

View posts in large calendar

Recent comments