views:

313

answers:

2

Hi,

Tracing this jquery autocomplete function, can someone explain in detail what is going on here?

function showResults() {
 // get the position of the input field right now (in case the DOM is shifted)
 var pos = findPos(input);
 // either use the specified width, or autocalculate based on form element
 var iWidth = (options.width > 0) ? options.width : $input.width();
 // reposition
 $results.css({
  width: parseInt(iWidth) + "px",
  top: (pos.y + input.offsetHeight) + "px",
  left: pos.x + "px"
 }).show();
};

It uses this function:

function findPos(obj) {
 var curleft = obj.offsetLeft || 0;
 var curtop = obj.offsetTop || 0;
 while (obj = obj.offsetParent) {
  curleft += obj.offsetLeft
  curtop += obj.offsetTop
 }
 return {x:curleft,y:curtop};
}

Reference: http://www.pengoworks.com/workshop/jquery/lib/jquery.autocomplete.js

+1  A: 

offsetLeft and offsetTop are properties that describe how many pixels obj is offset from it's containing element. What this function does is:

  1. Compute the offset of obj from its parent element and save these values in variables
  2. Set obj to be the parent element of the item last computed from
  3. Goto 1. Repeat until you have reached the top level of the DOM.

This calculates how many pixels that obj is from the top and left sides of the rendered page.

tj111
so it will always be obj = obj.offsetParent until it reaches the body tag?
Essentially, yes.
tj111
+1  A: 

Basically, it's figuring out the X and Y coordinates (left and top in CSS terms) of the input field you're using autocomplete on and setting the top and left CSS attributes of the autocomplete HTML to have it appear there. In other words, it's matching up the corners of the input Element and autocomplete layer so they appear at the same place (it's doing the same with widths and heights, too).

In the findPos function, we're basically walking back up the DOM tree getting the offsets (see Mozilla's dev center) of each Element from their parent (and eventually the body tag) to get the precise x and y coordinates of that input so that we can position the autocomplete layer at it's coordinates. We sum these, and wind up with the x and y values we pass back up to use in setting the left and top positions in CSS.

It's essentially copying the x and y position, height, and width of your input and applying them to the autocomplete layer so that they match up visually.

ajm