P is for Position

The fourth in a popular series of DOM scripting primers. This example demonstrates retrieving element style positions without computed styles.

A Defensible Position

This is useful for figuring the starting point for a move animation, drag operation or anything that must modify the position of the element relative to its current position. This is important as computed styles are sometimes unavailable or unusable (particularly in Internet Explorer).

The very simple example script is inline and should need little explanation (though at least some will follow in the near future). The pivotal function is getElementPositionStyles.

o = getElementPositionStyles(el);

The function returns an object with left, top, right and bottom properties. Styles that are indeterminate will result in null properties. The examples cover both relative and absolute position styles and fixed was tested successfully during development.

Note that none of the test elements has inline styles. Pixel units are used to make the results easily verifiable, but any units can be used with this technique.

Note that this technique will not work when both sides (e.g. left and right or top and bottom) have specified styles.

#firstone, #secondone { position:relative }
#thirdone, #fourthone { position:absolute }
#thirdone, #fourthone { top:0 }
#firstone { left:2px; top:-10px }
#secondone { right:2px; bottom:20px }
#thirdone { left:300px }
#fourthone { right:2px }

For those who do not care to wade through the style declarations, the expected results are:

  1. Left: 2, Right: null, Top: -10, Bottom: null
  2. Left: null, Right: 2, Top: null, Bottom: 20
  3. Left: 300, Right: null, Top: 0, Bottom: null
  4. Left: null, Right: 2, Top: 0, Bottom: null
Report

Other Primers

Home
dmark@cinsoft.net