Clicking the button will use Dom's
getXY method to get the position of the red element and pass it to the
setXY method, which will move the blue element to that position.
To illustrate the use of
getXY, we'll create a
foo and a
bar. When the document is clicked,
foo will move to the top left corner of
Start with some simple CSS rules, markup for the demo elements, and a button to trigger the demo:
Now we will define the function that moves
foo to the
xy position of
bar. The only argument of the
getXY method is either the ID of an HTMLElement, or an actual HTMLElement object. The
getXY method returns an array containing two values:
[x, y] where
x is the distance from the left edge of the document, and
y is the distance from the top edge of the document. The YUI Dom Collection provides a
setXY that accepts an array in the same format.
Next we will use the YUI Event Utility's
on method to listen for clicks on the button.
This is a simple example of how to use the
YAHOO.util.Dom.getXY method. One of the powerful things about this is that regardless of what is influencing the element's position, be it positioning (absolute, relative, etc.), margins, an
offsetParent (any positioned ancestor), or any other factors that may affect it,
getXY will return a position in document coordinates (e.g.
[0, 0] will be the upper left corner of the document).
Note: Logging and debugging is currently turned off for this example.
All YUI 2.x users should review the YUI 2.8.2 security bulletin, which discusses a vulnerability present in YUI 2.4.0-2.8.1.